[英]Laravel 5.2 - Eager load distant model in Polymorphic relation
我有一个用多态关系构建的类似系统。 我想在检索 Likes 时急切加载 likeable_type 的模型。 我需要做什么? 我试着添加
protected $with = ['Post'];
或者
protected $with = ['App\Post'];
到我的 Like 模型,但我得到的只是:
调用未定义的方法 Illuminate\\Database\\Query\\Builder::Post()
喜欢的型号:
class Like extends Model
{
use SoftDeletes;
protected $table = 'likeables';
protected $fillable = [
'user_id',
'likeable_id',
'likeable_type',
];
/**
* Get all of the owning likeable models.
*/
public function likeable()
{
return $this->morphTo();
}
}
岗位型号:
class Post extends Model
{
protected $fillable = [
'picture',
'description'
];
/**
*
* a post belongs to one user
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user(){
return $this->belongsTo('App\User');
}
/**
*
* a post has many comments
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
/**
* Get all of the post's likes.
*/
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
/**
*
* Simple Like System checks if liked
*
* @return bool
*/
public function getIsLikedAttribute()
{
$like = $this->likes()->whereUserId(Auth::id())->first();
return (!is_null($like)) ? true : false;
}
}
我通过将表从“likeables”重命名为“likes”解决了这个问题。
protected $table = 'likeables';
-> protected $table = 'likes';
现在我可以在检索类似这样的东西时检索远方关系:
$post = Post::find(6);
dd ($post->likes()->with('likeable')->get());
或者我可以像这样检索喜欢的实体:
$like = Like::find(1);
$likeable = $like->likeable;
dd($likeable);
在重命名表之前,结果为 Null .. 我仍然需要了解如何检索用户喜欢的所有实体。
Illuminate\\Database\\Query\\Builder::Post()
你有一个关于帖子的问题。
您可以使用“firstOrFailed()”获取这样的数据:
$data=table_name::where('$id','like',$id)->firstOrFailed();
或“get()”方法。 (这会随着关系而变化。)
这是关于多态关系的教程。 https://laravel.com/docs/5.3/eloquent-relationships#polymorphic-relations
如果您不能解决问题,请提供更多信息,如控制器、查看页面和迁移。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.