簡體   English   中英

Laravel:如何從具有關系的 3 個表中獲取數據

[英]Laravel: How to get data from 3 tables with relationship

我有 3 個表:

Customers

  • ID
  • 姓名

Sales

  • 顧客ID
  • 發售日期

Contacts

  • 顧客ID
  • 聯系日期

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循環中得到了一些結果。 但是,我無法從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熱切

$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM