[英]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.