我有两个模型,它们之间定义了多对多类型关系:User
belongsToMany
Post
。成功将$post
附加到$user->posts()
后,执行$user->posts()->find($post->id)
会返回null
。这是失败的代码:
if(!$user->posts()->exists($post)){
$user->posts()->attach($post);
}
// dd($user->posts()->exists($post)) // <-- true, hence the $post was successfully attached
$post = $user->posts()->find($post->id); // <-- null
目标是访问$post
记录的轴心。我怎样才能做到这一点?
// User
public function posts()
{
return $this->belongsToMany(Post::class, 'posts_users', 'user_id', 'post_id')
->withTimestamps()
->withPivot('viewed');
}
// Post
public function users()
{
return $this->belongsToMany(User::class, 'posts_users')
->withTimestamps()
->withPivot('viewed');
}
答案 0 :(得分:1)
你在关系班manyToMany
上,所以最好这样做:
if(!$user->posts()->where('id', $post->id)->count()){
$user->posts()->attach($post->id);
}
$post = $user->posts()->where('id', $post->id)->first();