附加后无法检索记录

时间:2016-05-10 20:49:07

标签: laravel laravel-5 eloquent laravel-5.2

我有两个模型,它们之间定义了多对多类型关系: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');
}

1 个答案:

答案 0 :(得分:1)

你在关系班manyToMany上,所以最好这样做:

if(!$user->posts()->where('id', $post->id)->count()){
    $user->posts()->attach($post->id);
}

$post = $user->posts()->where('id', $post->id)->first();