简体   繁体   English

如何在Laravel中为数据透视表编写关系?

[英]How can I write a relation for pivot table in Laravel?

Here is my table structure: 这是我的表结构:

// tickets
+----+------------+----------------------+--------+---------+-------------------+
| id |  subject   |        content       | closed | user_id | unique_product_id |
+----+------------+----------------------+--------+---------+-------------------+
| 1  | subject1   | question1            | 0      | 123     | 2                 |
+----+------------+----------------------+--------+---------+-------------------+

// unique_product
+----+---------------+------------+
| id | serial_number | product_id |
+----+---------------+------------+
| 1  | 2342rd34fc    | 3          |
| 2  | fg34gt4r5t    | 1          |
| 3  | 34ffvv4et6    | 3          |
+----+---------------+------------+

// products
+----+--------------+
| id |     name     | 
+----+--------------+
| 1  | Router-rb51  |
| 2  | Switch-sfx2  |
| 3  | Router-rb300 |
+----+--------------+

Now I have a collection of tickets like this: 现在,我有这样的tickets集合:

$tickets = tickets::where(user_id, "$user_id")->get();
foreach( $tickets as $ticket ){
    $ticket->{I need to get the name of product here}
}

I can write a relation in the tickets model like this: 我可以在tickets模型中编写如下关系:

public function unique_product()
{
    return $this->hasOne(unique_product::class, 'id', 'unique_product_id');
}

And I need one more relation to the products table for getting the name of product (ie Switch-sfx2 ). 而且我还需要一个与products表的关系以获取products名称(即Switch-sfx2 )。 How should I write that relation? 我应该如何写这种关系?

$tickets = tickets::where(user_id, "$user_id")->with('unique_product.product')->get();

You can take advantage eager loading using with() . 您可以利用with()加载。

but for using with('unique_product.product') You have to define the relation ships between unique_products and products. 但要with('unique_product.product')使用with('unique_product.product')则必须定义unique_products与产品之间的关系。

In your UniqueProduct model create a new relationship 在您的UniqueProduct模型中创建新关系

public function product()
{
    return $this->BelongsTo(Product::class, 'id', 'product_id');
}

After that you can access the column of a name like 之后,您可以访问名称列,例如

foreach( $tickets as $ticket ){
    $ticket->unique_product->product->name
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM