我想填充每個CustomerEvent
以及與CustomerEvent
相關的Customer
。使用關係填充laravel對象
當我循環訪問對象並調用$customerevent->customer
foreach對象時,我可以獲取與該事件相關的客戶,但是我可以在主對象中填充所有對象而無需循環每個事件?
我想要做這樣的事情:
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
這裏我的代碼:
表1: 「事件」
id, customer_id
爲表1 「CustomerEvent」 模式:
<?php
class CustomerEvent extends Eloquent{
protected $guarded = ['id'];
public $table = "event";
protected $softDelete = true;
public function scopeTypeOne($query)
{
$followUps = $query->where('type_id', '=', '1');
}
public function Customers()
{
return $this->belongsTo('Customer', 'customer_id');
}
}
表2: 「大客戶」
id
模型表2 「客戶」:
<?php class Customer extends BaseModel{
protected $guarded = ['id'];
}
EventController:
public function index()
{
$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;
dd($customersWithTypeOne);
}
我實際使用Laravel 4.0,所以我不得不升級得到這個功能。感謝您的回答 – oBo
$客戶=客戶:: whereHas( '事件',函數($查詢){ \t \t \t $查詢 - > typeOne(); \t \t}) - >與( '事件') - >得到(); – oBo