【问题标题】:Laravel Eloquent : retrieving an unique value with belongsToMany relationshipLaravel Eloquent : 通过 belongsToMany 关系检索唯一值
【发布时间】:2018-03-18 22:29:27
【问题描述】:

使用 Eloquent,我很难在三个表之间建立关系:

t_orders列出了所有的订单以及相关的customer_id

+----------+-------------+
| order_id | customer_id |
+----------+-------------+
|        1 |           5 |
|        2 |           3 |
|        3 |           1 |
+----------+-------------+

t_orders_items 列出每个订单的商品(fabrication_orders)

+----------+-------------------+
| order_id | fabrication_order |
+----------+-------------------+
|        1 |                 1 |
|        1 |                 2 |
|        2 |                 3 |
|      ... |               ... |
+----------+-------------------+

最后t_customer table 给了我一些关于客户的信息

+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
|           1 | Foo           |
|           3 | Bar           |
|           5 | Fun           |
+-------------+---------------+

我只是想知道给定fabrication_order(始终唯一)关联的客户端名称。所以fabrication_order = 2 我会得到Fun

阅读 Eloquent 的文档后,我认为 t_orders 会以某种方式扮演数据透视表的角色。

所以我写了如下关系:

class OrderItem extends Model
{
    ...
    public function customer(){
        return
            $this->belongsToMany('App\Customer', 't_orders','order_id',
            'customer_id', 'order_id', 'customer_id');
    }
}

唯一的缺点是它返回一个集合而不是唯一值。

"customer":[{"customer_id":5,"customer_name":"Fun"..}]

我希望达到:

"customer":{"customer_id":5,"customer_name":"Fun"..}

当然,集合只有一个价值,但我想写得更干净。

【问题讨论】:

    标签: eloquent


    【解决方案1】:

    您可以使用两个独立的BelongsTo 关系:

    OrderItemOrder, OrderCustomer

    然后像这样访问客户:

    $orderItem->order->customer
    

    如果您需要它作为 JSON 字符串中的属性:

    class OrderItem extends Model
    {
        $appends = ['customer'];
    
        public function getCustomerAttribute() {
            return $this->order->customer;
        }
    }
    

    【讨论】:

    • OrderCustomer 将在订单模型中是这样吗?
    猜你喜欢
    • 2020-03-04
    • 2015-02-11
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2020-02-02
    • 2014-12-10
    • 2019-10-01
    • 2023-03-04
    相关资源
    最近更新 更多