此$checkLike = $user->places->contains($placeId);
旨在检查用户是否喜欢带有placeId的景点,但是,即使数据库中有记录,它仍会返回false。
我有3张这样的桌子:
Table: Users
Columns: id, username, password
Table: Places
Columns: id, place_id
Table: Place_User
Columns: id, user_id, place_id
目前,我在每个表中都有1条记录,如下所示:
Users Place_User Places
6, Admin, Admin
1, 6, 15
15, b4b8adfb46dfbabdf864b
所以我假设$checkLike = $user->places->contains($placeId);
在已经有记录时将返回true。可悲的是事实并非如此。
我的模特:
class User extends \Eloquent implements Authenticatable
{
use AuthenticableTrait;
public function places(){
return $this->belongsToMany('App\Place');
}
}
和
class Place extends Model
{
public function user(){
return $this->belongsToMany('App\User');
}
}
答案 0 :(得分:2)
仅当您将->contains
设置为某个地方的$placeId
而不是id
的{{1}}时,place_id
方法才有效。
以以下示例为例:
App\Place
但是,以下内容将返回false,因为它引用了$placeId = 15;
$user->places->contains($placeId); // true
属性:
place_id
要实现上述目标,您必须传递一个callable并比较right属性:
$placeId = 'b4b8adfb46dfbabdf864b';
$user->places->contains($placeId); // false