[英]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.