我有与多对多关系的物品和用户。 我想向用户展示不属于他自己的所有项目,我该如何展示?
编辑:
public function user()
{
return $this->belongsToMany('App\User', 'interest_user');
}
public function interests()
{
return $this->belongsToMany('App\Interest', 'interest_user');
}
EDIT2: 我更改了代码,但收到了相同的错误消息
public function user()
{
return $this->belongsToMany(User::class);
}
public function interests()
{
return $this->belongsToMany(Interest::class);
}
Schema::create('interest_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('interest_id')->unsigned();
$table->foreign('interest_id')->references('id')->on('interests')->onDelete('cascade');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
$suggestinterests = Interest::whereHas('user_id', function ($q) use ($user) {
$q->where('user_id', '!=', $user);
})->get();
Errormessage:调用未定义的方法App \ Interest :: whereHas()
EDIT3: 这段代码有效!
$suggestinterests = \App\Interest::whereHas('user', function ($q){
$q->where('user_id', '!=', auth()->id());
})->get();
答案 0 :(得分:2)
class User
{
public function items()
{
return $this->belongsToMany(Item::class);
}
}
class Item
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('items', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('item_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->unsigned()->index();
$table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
检索记录:
$availableItems = Item::whereHas('user_id', function ($q) use (Auth::user()->id {
$q->where('user_id', '!=', Auth::user()->id);
})->get();
这是非常原始的,你可能需要适应它!
答案 1 :(得分:0)
我花了一些时间才弄清楚
$all_items_but_excluded_user_items = DB::table('interests')
->select('name',DB::raw('interest_user.interest_id as pivot_interest_id'),
DB::raw('interest_user.user_id as pivot_user_id'))
->join('interest_user','interests.id','=','interest_user.item_id')
->where('interest_user.user_id','!=',$user->id)
->get();