我正在为照片帖子编写一个网站,并且我有这些与喜欢相关的功能(它们确定用户是否喜欢特定的帖子)
后模型:
public function likes()
{
return $this->hasMany('Like');
}
public function isLiked()
{
return $this->likes()->where('user_id', Auth::user()->id);
}
例如后 Controller 函数:
public function postsByType($type)
{
if($this->user){
$posts = Post::with('isLiked')->where('type', '=', $type)->paginate(12);
} else {
$posts = Post::where('type', '=', $type)->paginate(12);
}
return $posts;
}
当用户未登录时,不运行查询,有什么方法可以在 MODEL 函数中返回 null?
我想避免在后 Controller 中写if
我考虑过以下解决方案,但它不起作用...
public function isFollowing()
{
return $this->setRelation('isFollowing', null);
}
出现这个错误:
调用未定义的方法 Illuminate\Database\Query\Builder::addEagerConstraints()
最佳答案
因为你可能总是想获取关系(除非没有用户登录)我建议你在你的模型中做这样的事情:
(我还将关系重命名为 liked
,稍后您会看到原因)
public function newQuery(){
$query = parent::newQuery();
if(Auth::check()){
$query->with('liked');
}
return $query;
}
现在每次使用模型运行查询时,如果用户已登录,将添加 with('isLiked')
。
不过还有一个问题。如果您访问 isLiked
,查询将无论如何运行。甚至对于每个帖子,因为它不是急于加载的。您可以通过添加属性访问器来解决这个问题:
public function getIsLikedAttribute(){
if(Auth::guest) return false;
return ! $this->liked->isEmpty();
}
所以在你看来你可以这样做:
@if($post->isLiked)
注意:将 newQuery()
中的内容移动到全局范围会更好。请务必在 the documentation 中查看如何执行此操作如果你有兴趣。
这是一个范围示例。创建一个类,我们称它为 LikedScope
:
class LikedScope implements Illuminate\Database\Eloquent\ScopeInterface {
public function apply(Builder $builder, Model $model){
if(Auth::check()){
$builder->with('liked');
}
}
public function remove(Builder $builder, Model $model){
}
}
然后将其添加到您的模型中:
public static function boot(){
parent::boot();
static::addGlobalScope(new LikedScope);
}
关于php - Laravel 模型返回空关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28570318/