簡體   English   中英

如何在Laravel中為數據透視表編寫關系?

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

這是我的表結構:

// 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 |
+----+--------------+

現在,我有這樣的tickets集合:

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

我可以在tickets模型中編寫如下關系:

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

而且我還需要一個與products表的關系以獲取products名稱(即Switch-sfx2 )。 我應該如何寫這種關系?

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

您可以利用with()加載。

但要with('unique_product.product')使用with('unique_product.product')則必須定義unique_products與產品之間的關系。

在您的UniqueProduct模型中創建新關系

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

之后,您可以訪問名稱列,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM