gpt4 book ai didi

Laravel:如何从3个有关系的表中获取数据

转载 作者:行者123 更新时间:2023-12-02 16:19:01 25 4
gpt4 key购买 nike

我有 3 个表:

客户

  • ID
  • 姓名

销售

  • customer_id
  • 促销日期

联系人

  • customer_id
  • 联系日期

contacts 表中没有任何更新操作。每个进程都会在 contacts 表中打开一条新记录。因此,一位用户可以在 contacts 表中拥有多条记录。

这是我在模型中的关系:

客户

public function contacts()
{
return $this->hasMany(Contact::class);
}

public function sales()
{
return $this->hasMany(Sale::class);
}

联系方式

public function customer()
{
return $this->belongsTo('App\Customer', 'customer_id');
}

促销

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();

在blade 文件中,我在foreach 循环中得到了一些结果。但是,我无法从 salescontacts 表中获取相关数据。

@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 eager returned:

$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();

如果您愿意,可以声明 last_contact 并附加 where:

public function latest_contact()
{
return $this->hasOne(Contact::class)
->where('result', 'UNCALLED')
->latest('contact_date');
}

这样所有其他查询都应该更容易。我希望这可以帮助你。

关于Laravel:如何从3个有关系的表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57773384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com