dongwen7187
2019-02-19 01:12
浏览 41
已采纳

有没有办法将此RAW查询转换为Eloquent?

I have this line of query that works on MySQL via localhost and i want to use it on my Laravel but i dont know how to convert or translate my code into Eloquent.

The 2 models are in relationship with each other. this is what i tried with my code.

Statuses

public function reqs(){
        return $this->belongsTo('App\Reqs','reqs_id','id');
}

Reqs

public function statuses()
{
    return $this->hasMany('App\Statuses','reqs_id','id');
}

This is what i tried and it cant get what i want

$reqs = Statuses::with('reqs')->
where('status','=',$status)->
where('user_id','=',auth()->user()->id)->get();

This on the other hand is working

DB::select('SELECT * from `statuses`, `reqs`
            WHERE `statuses`.`status` = ?
            AND `reqs`.`id` = `statuses`.`reqs_id`
            AND `reqs`.`user_id` = ?
            ', [$status,auth()->user()->id]);

i got what i expected but i want to know if there is a eloquent way. THANKS.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douji8549 2019-02-19 01:47
    已采纳

    You can't select from two tables with Eloquent, you need to explicitly join the other table on. You don't need the select() part of this query but you probably should be explicit about what fields you want so that you get the data you expect.

    Status::select('statuses.*')
        ->join('reqs', 'reqs.id', '=', 'statuses.reqs_id')
        ->where('statuses.status', $status)
        ->where('reqs.user_id', auth()->id())
        ->get();
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题