需要对所有user_id不等于我们的位置进行采样
Need to take a sample of all positions where user_id is not equal to ours
有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));
}
我做错了什么?如果可能并给出解释
您可能想要 lists('post_id')
。
然而 whereDoesntHave
有一个更好的方法:
$userId = $this->id;
$posts = Post::whereDoesntHave('users', function($q) use ($userId){
$q->where('user_id', $userId);
})->get();
假设 $this->id
包含您的用户 ID,试试这个:
$posts = Post::whereHas('users', function($q) {
$q->whereNotIn( 'id', [$this->id])
})->get();
方法whereHas()
选择属于用户的帖子,这些帖子在闭包中满足条件。这个条件 - 方法 whereNotIn()
- 检查用户 ID 是否与 $this->id
.
不同
有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));
}
我做错了什么?如果可能并给出解释
您可能想要 lists('post_id')
。
然而 whereDoesntHave
有一个更好的方法:
$userId = $this->id;
$posts = Post::whereDoesntHave('users', function($q) use ($userId){
$q->where('user_id', $userId);
})->get();
假设 $this->id
包含您的用户 ID,试试这个:
$posts = Post::whereHas('users', function($q) {
$q->whereNotIn( 'id', [$this->id])
})->get();
方法whereHas()
选择属于用户的帖子,这些帖子在闭包中满足条件。这个条件 - 方法 whereNotIn()
- 检查用户 ID 是否与 $this->id
.