我目前正在列出各种提要中的项目,此提要显示"自由泳"列表和自由泳的点赞数量,我需要基本上说用户是否喜欢提要中的自由泳。
我尝试过的:
我喜欢的型号:
class Likes extends Model {
use SoftDeletes;
protected $table = 'Likes';
protected $fillable = ['id', 'userID', 'freestyleID'];
protected $dates = ['deleted_at'];
public function variantOne()
{
return $this->beat()->where('TrackVariantID', '1')->first();
}
public function freestyle() {
return $this->belongsTo(Freestyle::class, 'freestyleID', 'id');
}
public function user() {
return $this->hasMany(User::class, 'userID', 'id');
}
}
在我的自由泳模型中:
public function likes()
{
return $this->belongsToMany('App'User', 'Likes', 'freestyleID', 'userID');
}
public function getLike($user) {
$like = $this->likes()->where('userID', $user)->first();
var_dump($like);
return ($like) ? $like : false;
}
我的控制器:
$freestyleLists = Freestyle::with('users')
->with('beats')
->with('likes')
->where('active', 1)
->orderBy('id', 'desc')
->paginate(10);
最后,我点击getLikes()方法的地方:
<p>{{print_r($freestyleList->getLike($user))}}</p>
收到的答复:
NULL 1 (for every freestyle in the feed)
我觉得我好像错过了一些显而易见的东西,或者忽略了这段关系。
如果我错过了什么,请告诉我。
取而代之的是:
$like = $this->likes()->where('userID', $user)->first();
尝试:
$like = $this->likes->filter(function ($l) use ($user) { return $l->userID == $user->id;});
然后,如果 count($like)> 0,您将知道用户是否喜欢自由泳。