用户模型:
public function favorites()
{
return $this->hasMany(Favorite::class);
}主计长:
//return auth()->user()->favorites()->get();
//return auth()->user()->favorites;有人能解释一下这两种代码之间的差异吗?我什么时候该用每一个?
发布于 2022-09-05 13:36:21
让我实际解释一下:
如果上面的查询如下所示
// return auth()->user()->favorites()->where('active', true)->get();
// return auth()->user()->favorites->where('active', true);然后它的SQL查询如下
// SQL of first query
select * from `favorites` where `favorites`.`user_id` = 1 and `favorites`.`user_id` is not null and `active` = 1
// SQL of second query
select * from `favorites` where `favorites`.`user_id` = 1 and `favorites`.`user_id` is not null您看到了两种SQL?的不同之处吗?
现在,让我用文字解释一下:
如果您在上面的favorites()之后添加了一些条件,它将从数据库中获取所有过滤的结果。但是,如果在favorites之后添加一些条件,它将过滤已经从数据库中获取的结果。
虽然我不擅长解释,但我希望您能清楚地理解这两种代码之间的关系。
https://stackoverflow.com/questions/73608220
复制相似问题