【问题标题】:Populate laravel object with relationships用关系填充 laravel 对象
【发布时间】:2014-01-08 19:08:10
【问题描述】:

我想用与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'];
}

事件控制器:

public function index()
{
    $typeOne = CustomerEvent::typeOne()->get();
    $customersWithTypeOne = $typeOne->Customers;
    dd($customersWithTypeOne);
}

【问题讨论】:

    标签: laravel laravel-4


    【解决方案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()
    

    【讨论】:

    • 我实际使用的是 Laravel 4.0,所以我必须升级才能获得这个功能。感谢您的回答
    • $customers = Customer::whereHas('events', function($query){ $query->typeOne(); })->with('events')->get();
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 2019-09-14
      • 2014-03-07
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多