[英]How can i filter pivot table with One to Many relation inside - Laravel 7
[英]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.