[英]Laravel get data from two tables connected with many to many relationship
[英]Laravel: How to get data from 3 tables with relationship
我有 3 個表:
Customers
Sales
Contacts
contacts
表中沒有任何更新操作。 每個進程在contacts
表中打開一個新記錄。 因此,一個用戶可以在contacts
表中擁有多個記錄。
這是我在模型中的關系:
Customer
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function sales()
{
return $this->hasMany(Sale::class);
}
Contact
public function customer()
{
return $this->belongsTo('App\Customer', 'customer_id');
}
Sale
public function customer()
{
return $this->belongsTo('App\Customer');
}
我想擁有contacts
表的最新記錄,並使其與其他相關表連接。
這是我嘗試過的查詢:
$record = Contact::groupBy('customer_id')
->select(DB::raw('max(id)'));
$result = Customer::query();
$result->where('is_active', 'YES');
$result->with('sales');
$result->whereHas('contacts', function ($q) use($record){
return $q->whereIn('id', $record)->where('result', 'UNCALLED');
});
return $result->get();
在刀片文件中,我在foreach
循環中得到了一些結果。 但是,我無法從sales
和contacts
表中獲取相關數據。
@foreach($result as $item)
@foreach($item->sales as $sale) // Has no output and gives error: Invalid argument supplied for foreach()
@foreach($item->contacts as $contact) // Has no output and gives error: Invalid argument supplied for foreach()
誰能幫助我如何顯示銷售和聯系日期? 或者任何關於如何提高此代碼質量的想法?
如果您想要聯系人的最新記錄,您可以在Customer
模型上聲明另一個關系,例如:
public function latest_contact()
{
return $this->hasOne(Contact::class)->latest('contact_date');
}
順便說一句,如果你有一個hasMany
,你總是可以聲明一個或多個hasOne
附加關系,如果使用的外鍵相同。
通過這種方式,您可以檢索加載了Customer
模型的latest_contact
熱切:
$customer = Customer::with('latest_contact')->find($id);
或者在您的查詢中使用這種關系,例如:
$customers = Customer::where('is_active', 'YES')
->with('sales')
->with('contacts')
->whereHas('last_contact', function ($q){
return $q->where('result', 'UNCALLED');
})->get();
或者那個:
$customers = Customer::where('is_active', 'YES')
->with('sales')
->with('contacts')
->with('last_contact', function ($q){
return $q->where('result', 'UNCALLED');
})->get();
如果您願意,您可以使用額外的where
聲明last_contact
:
public function latest_contact()
{
return $this->hasOne(Contact::class)
->where('result', 'UNCALLED')
->latest('contact_date');
}
這樣所有其他查詢應該更容易。 我希望這可以幫助你。
我不確定,但是您可以嘗試執行以下操作:
return Customer::where('is_active', 'YES')
->with([
'sale',
'contact' => function ($query) use($record) {
return $query->whereIn('id', $record)->where('result', 'UNCALLED');
}
])->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.