[英]Foreign Key relations not working in laravel
我做了兩個表Inventory和Inventory_images。 庫存表的主鍵是庫存表圖像的外鍵,現在我正在嘗試獲取相同庫存的所有圖像,但會出錯。 這是我的代碼
庫存模型:
/**
* The table name that should be hidden from other modules
*/
protected $table = 'inventories';
protected $PrimaryKey = 'id';
public function test(){
return $this->belongsTo('App\InventoryImage', 'i_id');
}
庫存圖片模型:
protected $table = 'inventory_images';
protected $PrimaryKey = 'id';
public function inv_det(){
return $this->belongsTo('App\Inventory', 'id');
}
控制器:
$inventory = Inventory::with('test')->orderBy('id', 'DESC')->paginate('10');
dd($inventory);
可以請一個人幫我找出問題所在嗎
您在代碼中犯了一些錯誤,應該首先解決(這可能會幫助您解決問題)。
首先,要覆蓋主鍵的變量名應該是$primaryKey
而不是$PrimaryKey
(變量名通常總是以小寫字母開頭。盡管如此,這應該沒有任何影響,因為Laravel假定主鍵字段始終以id
命名。
更重要的是,在兩種情況下, belongsTo
使用belongsTo
方法,盡管在一種情況下,應為hasMany
。 在1-n關系中,父模型應返回hasMany
關系,而子模型(包含帶有外鍵的列)應belongsTo
。
此外,hasMany或belongsTo方法的第二個參數是外鍵列名稱,以防與模型的蛇形表示形式不同(由_id
附加)。 因此,如果您的inventory_images
表具有一個除inventory_id
之外的不同名稱的外鍵列,則需要使用正確的名稱傳遞第二個參數。 我假設您的外鍵名稱是i_id
,所以您需要將其傳遞給兩個函數。
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many
請檢查是否可行:
/**
* The table name that should be hidden from other modules
*/
protected $table = 'inventories';
protected $primaryKey = 'id';
public function test(){
return $this->hasMany('App\InventoryImage', 'i_id');
}
和子表:
protected $table = 'inventory_images';
protected $primaryKey = 'id';
public function inv_det(){
return $this->belongsTo('App\Inventory', 'i_id');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.