2014-01-08 64 views
0

我想填充每個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); 
} 

回答

1

從你的數據庫方案我看到客戶有很多事件,所以我會建議在你的模型中定義這種關係Customer模型。

class Customer extends BaseModel{ 
    protected $guarded = ['id']; 

    public function events() 
    { 
     return $this->hasMany('CustomerEvent', 'customer_id'); 
    } 
} 

然後你就可以查詢客戶的事件:

$customersWithTypeOne = Customer::whereHas('events', function($query){ 
    $query->where('type_id', 1); 
})->get() 
+0

我實際使用Laravel 4.0,所以我不得不升級得到這個功能。感謝您的回答 – oBo

+0

$客戶=客戶:: whereHas( '事件',函數($查詢){ \t \t \t $查詢 - > typeOne(); \t \t}) - >與( '事件') - >得到(); – oBo