首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Laravel一对一关系和查询

Laravel一对一关系和查询
EN

Stack Overflow用户
提问于 2018-10-19 01:25:16
回答 1查看 95关注 0票数 0

我有一些客户已经被归类为(个人-公司),我想将主表和子表中的所有客户信息放到一个查询中,我尝试了很多次,但都没有找到解决方案。我在本主题末尾的尝试

我的表:

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

我的RelationShips:

CustomerType.php

代码语言:javascript
复制
class CustomerType extends Model
{
    public function customers()
    {
        return $this->hasMany('App\Customer');
    }
}

Customer.php

代码语言:javascript
复制
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

代码语言:javascript
复制
class CustomerIndividual extends Model
{
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }
}

CustomerCompany.php

代码语言:javascript
复制
class CustomerCompany extends Model
{
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }
}

我希望输出如下所示:

代码语言:javascript
复制
[
  {
     "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"
     }
  }
]

以下是我的尝试:

代码语言:javascript
复制
return Customer::with(['person', 'company'])->get();

代码语言:javascript
复制
$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;

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

EN

回答 1

Stack Overflow用户

发布于 2018-10-19 01:34:45

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

假设$q->with('person')是一个对象:

代码语言:javascript
复制
$collection = new \Illuminate\Database\Eloquent\Collection;

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

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

$c = $collection->flatten();
return $c;

文档:Here

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52879451

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档