需要对user_id不等于我们的所有位置进行采样

时间:2015-02-10 08:53:14

标签: laravel-4 eloquent

有3张桌子

用户 帖子 post_user(id,post_id,user_id)

class Post extends Eloquent {

protected $table = 'posts';
public $timestamps = true;

public function users()
{
    return $this->belongsToMany('User');
}

}

class Users extends Eloquent {

    protected $table = 'users';
protected $hidden = array('password', 'remember_token');

public function posts()
{
    return $this->belongsToMany('Post');
}

}

控制器

 public function application()

{

    $posts = Post::find(1);
    $user = DB::table('post_user')->where('user_id', '=', $this->id)->lists('user_id');

    $posts = Post::whereNotIn('id', $user)->get();
    return View::make('applications')->with(array('posts' => $posts));


}

我做错了什么?如果可能的话有解释

2 个答案:

答案 0 :(得分:0)

您可能想要lists('post_id')

然而whereDoesntHave有一个更好的方式:

$userId = $this->id;
$posts = Post::whereDoesntHave('users', function($q) use ($userId){
    $q->where('user_id', $userId);
})->get();

答案 1 :(得分:0)

假设$this->id包含您的用户ID,请尝试以下操作:

$posts = Post::whereHas('users', function($q) {
    $q->whereNotIn( 'id', [$this->id])
})->get();

方法whereHas()选择属于用户的帖子,这些用户已满足Closure内的条件。这个条件 - 方法whereNotIn() - 检查用户ID是否与$this->id不同。