Laravel一对一关系和查询

时间:2018-10-18 17:25:16

标签: laravel relationship one-to-one

我的客户已被分类为(个人公司),我想从主表和子表中获取所有客户信息,并进行一个查询,我尝试了很多次,但没有找到解决方案..我的尝试在本主题末尾

我的桌子:

customer_type

  • id
  • type

客户

  • id
  • address
  • customer_type_id

customer_individual

  • id
  • first_name
  • last_name
  • customer_id

customer_company

  • id
  • company_name
  • logo
  • customer_id

我的关系船舶:

CustomerType.php

class CustomerType extends Model
{
    public function customers()
    {
        return $this->hasMany('App\Customer');
    }
}

Customer.php

class Customer extends Model
{
    public function customer_type()
    {
        return $this->belongsTo('App\CustomerType');
    }

    public function more()
    {
        $related = ($this->customer_type_id == '1') ? 
        'App\CustomerIndividual' : 'App\CustomerCompany'; 
             // 1 => individual

        return $this->hasOne($related, 'customer_id');
    }
}

CustomerIndividual.php

class CustomerIndividual extends Model
{
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }
}

CustomerCompany.php

class CustomerCompany extends Model
{
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }
}

我希望输出如下:

[
  {
     "id": 1,
     "customer_type_id": 1,
     "address": "New York",
     "more": {
        "id": 1,
        "customer_id": 1,
        "first_name": "John",
        "last_name": "doe"
     }
  },
  {
     "id": 2,
     "customer_type_id": 2,
     "address": "london",
     "more": {
        "id": 2,
        "customer_id": 2,
        "name": "ANA IT Company",
        "logo": "analogo.png"
     }
  }
]


这些是我的尝试:

return Customer::with(['person', 'company'])->get();

$customers = Customer::query();

$customers->when($customers->customer_type_id === 1, function($q){
   return $q->with('person');
});

$customers->when($customers->customer_type_id === 2, function($q){
   return $q->with('company');
});

$c = $customers->get();
return $c;

我希望在这里找到解决方案。

1 个答案:

答案 0 :(得分:0)

您可以做的是创建一个新集合并将其添加到其中。

假设Thread.sleep是一个对象:

$q->with('person')

文档:Here