我想填充每个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