[英]How to retrieve the data from multiple table relation in mysql
我正在PHP Laravel 5.5中的一個項目中工作。 我有表tbl_borrower,tbl_property_owner,tbl_property,tbl_property_borrower。 表的結構是這樣的。 在報告中,我必須顯示借款人詳細信息,財產所有者詳細信息,已分配的財產詳細信息。 報告應該是這樣的。
我試圖在這樣的模型中建立一對多的關系。
public function properties()
{
return $this->hasMany('App\Property','property_owner_id');
}
public function assigned_property()
{
return $this->hasMany('App\PropertyBorrower','property_id');
}
這樣,我可以檢索財產所有人的財產詳細信息,但是我無法獲得根據財產所有人分配給借款人的值。 提前致謝。
嘗試如下
use App\Property;
use App\PropertyBorrower;
public function properties()
{
return $this->hasMany(Property::class, 'property_owner_id', 'id');
}
public function assigned_property()
{
return $this->hasMany(PropertyBorrower::class, 'property_id', 'id');
}
在您的借款人模型中
public function borrower()
{
return $this->belongsTo(PropertyBorrower::class, 'id', 'borrower_id');
}
關系中有兩種情況。 1.基於正確的命名轉換,僅給出模型名稱。
Example :
consider you have users table and you have another table like comments table.
Users Table fields = id, name
Comments Table = id, comments, user_id.
在這里,您遵循了正確的命名轉換(如user_id),因此您只需提供如下的模型名稱,
return $this->hasOne('App\Comment'); or return $this->hasOne(Comment::class)
不同的外鍵名稱。
范例:
考慮您有用戶表,還有另一個表,例如注釋表。
Users Table fields = id, name Comments Table = id, comments, author_id.
在這里,外鍵與表名相比有所不同,因此您必須在關系函數中告訴鍵。
return $this->hasOne('App\Comment', 'author_id', 'id');
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.