【问题标题】:Laravel 5 eloquent include the row of the other table from the foreign key of the 2nd joined tableLaravel 5 eloquent 包括来自第二个连接表的外键的另一个表的行
【发布时间】:2016-01-11 10:12:17
【问题描述】:

我有 3 个示例模型

  1. 客户

    身份证

  2. 订购

    身份证

    customer_id

    deliver_address_id

  3. 客户地址

    身份证 customer_id

    街道

    国家

客户可以在个人资料中保存多个地址,但每个订单只能选择一个地址。

我想使用 laravel 5 eloquent 在一次查询中获取包括地址在内的所有客户订单。我是 laravel 的新手,所以很难查询复杂的关系表。

【问题讨论】:

    标签: php laravel laravel-4 laravel-5 eloquent


    【解决方案1】:
    class Customer extends Model {
    
        $table = 'customers';
    
        function addresses(){
            return $this->hasMany(Address::class, 'customer_id');
        }
    
        function orders(){
            return $this->hasMany(Order::class, 'customer_id');
        }
    
    }
    
    class Order extends Model {
    
        $table = 'orders';
    
        function address(){
            return $this->belongsTo(Address::class, 'address_id');
        }
    
        function customer() {
            return $this->belongsTo(Customer::class, 'customer_id');
        }
    }
    
    class Address extends Model{
    
        $table = 'customer_addresses';
    
        function customer(){
            return $this->belongsTo(Customer::class, 'customer_id');
        }
    
    }
    
    
    TABLES : 
    1 customers
    
            id
    
    2 orders
    
            id
    
            customer_id
    
            address_id
    
    3 customer_addresses
    
            id
    
            customer_id
    
            street
    
            country
    

    【讨论】:

    • 但是如何使用 laravel eloquent 在单个查询中构造它?使用雄辩的关系方法..我想获得所有客户订单,包括地址(树和国家)..谢谢
    • $cutomer->orders()->with('address')->get()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2020-12-30
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    相关资源
    最近更新 更多