【问题标题】:Laravel Relationship between Three ModelsLaravel 三种模型之间的关系
【发布时间】:2019-09-10 09:19:45
【问题描述】:
sold_items:
id    order_id   customer_id   name      
--    --------   -----------   ----
1     5          14            An object

orders:
id      po_num
--      ------
...     ...
5       123


customers:
id      name
--      ----
...     ...
14      John Doe

SoldItem 有一个order_id 和一个customer_id

我正在尝试通过SoldItem 定义Order 与其Customer 之间的hasOne 关系,而无需在Order 中插入customer_id 列模特的桌子。

hasOneThrough 似乎是解决方案,但我不知道从那里去哪里,或者这就是答案?

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $timestamps = false;
    protected $guarded = ['id'];

    public function sold_items()
    {
        return $this->hasMany('App\SoldItem');
    }

    public function customer()
    {
        // return $this->hasOneThrough();
    }
}

【问题讨论】:

    标签: mysql laravel-5 eloquent eloquent-relationship


    【解决方案1】:

    对于客户模型

    {
    
        public function sold_items()
        {
            return $this->hasMany('App\SoldItem');
        }
    
    
    }
    

    对于订单模型

    {
    
        public function sold_items()
        {
            return $this->hasOne('App\SoldItem');
        }
    
    
    }
    

    SoldItem 模型

    {
    
        public function customer()
        {
            return $this->belongsto('App\Cutomer');
        }
    
         public function order()
        {
            return $this->belongsto('App\Order');
        }
    
    }
    

    我更喜欢先处理它们的关系,然后使用 with() 函数来获取它们的值。

    use App\Customer;
    
    $customer = Customer::with('sold_items','sold_items.order')->get();
    

    【讨论】:

      【解决方案2】:

      我最终通过其sold_itemsOrderCustomer 设为attribute

      <?php
      
      namespace App;
      
      use Illuminate\Database\Eloquent\Model;
      
      class Order extends Model
      {
          public $timestamps = false;
          protected $guarded = ['id'];
      
          public function sold_items()
          {
              return $this->hasMany('App\SoldItem');
          }
      
          public function getCustomerAttribute()
          {
              return $this->sold_items->first()->customer;
          }
      }
      
      

      【讨论】:

        猜你喜欢
        • 2021-05-16
        • 1970-01-01
        • 2019-05-07
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 1970-01-01
        • 2016-08-17
        • 2018-05-23
        相关资源
        最近更新 更多