这是原始查询的预期结果
$sql = 'SELECT c.*
FROM catalogs c
LEFT JOIN (SELECT s.* FROM stock s WHERE s.date = "'.$dateOption.'") as sb
on sb.id_product = c.id_product
WHERE c.id_branch = '.Auth::user()->id_branch.';
$list = DB::select($sql);
我使用查询构建器修改了它,但结果不正确
$lists = DB::table('catalogs')
->leftJoin('stock', 's.id_product','=','catalogs.id_product')
->where('s.date',$dateOption)
->where('catalogs.id_branch',Auth::user()->id_branch)
->get();
任何人都可以告诉我应该如何在查询构建器中编写它?
答案 0 :(得分:0)
传递给hasOne方法的第一个参数是相关模型的名称。一旦定义了关系,我们就可以使用Eloquent的动态属性检索相关记录。动态属性允许您访问关系方法,就好像它们是在模型上定义的属性一样:
命名空间App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
然后你可以像下面一样得到联接。
$phone = User::find(1)->phone;