2014-01-08 132 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