用关系填充laravel对象

时间:2014-01-08 09:53:19

标签: laravel laravel-4

我希望使用与CustomerEvent相关的Customer填充每个CustomerEvent

当我遍历对象并调用$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);
}

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

也许Ardent可以帮助你:https://github.com/laravelbook/ardent 它是Eloquent模型的扩展,非常受欢迎。