簡體   English   中英

Laravel屬於ToMany未返回結果

[英]Laravel belongsToMany not returning results

我設置了以下架構:

用戶:

  • ID

部門:

  • ID

department_user:

  • ID
  • department_id
  • 用戶身份

我還建立了以下關系:

用戶模型

public function departments()
{
    return $this->belongsToMany('App\Resources\Eloquent\Models\Department', 'department_users');
}

部門模式

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

由於某些原因,當我嘗試通過用戶模型$user->departments ,它不起作用-但是$department->users可以。

輸出雄辯的查詢如下:

select `departments`.*, `department_users`.`user_id` as `pivot_user_id`, `department_users`.`department_id` as `pivot_department_id` from `departments` inner join `department_users` on `departments`.`id` = `department_users`.`department_id` where `department_users`.`user_id` is null

我似乎無法弄清楚為什么它應該在查找用戶ID時才查看department_users.user_id是否為null。

有任何想法嗎?

你為什么不設置你的模型像它在文檔中建議在這里

因此,您的模型將如下所示:

用戶模型

public function departments()
{
    return $this->belongsToMany('path\to\your\model\Department');
}

部門模式

public function users()
{
    return $this->belongsToMany(path\to\your\model\User);
}

Eloquent會按字母順序將兩個相關的模型名稱連接在一起。因此,在定義關系時不需要額外的參數,並且默認情況下,Laravel也使模型鍵出現在數據透視對象上。 然后您可以執行以下操作:

$department = path\to\your\model\Department::find(1);

foreach ($department->users as $user) {
    echo $user;
}

由於某種原因,如果我建立以下關系-它將起作用。

 return $this->belongsToMany(Department::class, 'department_users')->orWhere('department_users.user_id', $this->id);

如果有人知道為什么,請告訴我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM