[英]laravel eloquent belongsTo fetches wrong data
我有兩張桌子。 一個包含用戶,另一個包含會議。 每次會議都屬於一個用戶。
會議會議
class Meeting extends Model {
protected $table = 'meetings';
protected $primaryKey = 'owner_id';
/**
* A meeting belongs to exact one User
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user(){
return $this->belongsTo(User::class, 'id');
}}
用戶
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
protected $primaryKey = 'id';
/**
* One User can have many Meetings
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function meetings(){
return $this->hasMany(Meeting::class, 'owner_id');
}
我用獲取數據
$meetings = Meeting::with('user')->get();
但是不知何故我沒有得到相關的用戶。 它只是遍歷數據庫中的所有用戶,如果沒有更多用戶,則中斷。
我到底在做什么錯? o
讓我們嘗試更改它:
public function user(){
return $this->belongsTo(User::class, 'id');
}
至
public function user(){
return $this->belongsTo(User::class, 'owner_id', 'id');
}
查看您的Meeting
模型,有2件奇怪的事情:
protected $primaryKey = 'owner_id';
這是為什么? 這里不應該是id
嗎?
第二件事:
public function user(){
return $this->belongsTo(User::class, 'id');
}
可能在這里,而不是id
您應該使用owner_id
。
綜上所述,似乎您為主鍵和關系設置了錯誤的鍵,這可能是關系無法正常工作的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.