[英]Laravel Eloquent one to many relationship, dynamically adding query to the related table
[英]laravel: convert many to many (but only one related item) mysql query to a laravel query
嗨,我在将一直在研究的mysql查询转换为laravel雄辩的查询时遇到麻烦,需要一些帮助。 我有一个预订表,该表链接到具有多对多关系的产品表。 我想取消所有预订,只提取找到的第一个产品,无论与预订相关的产品有多少。 这是我的sql:
SELECT reservations.id,
reservations.play_date,
reservations.group_size,
reservations.status,
reservations.event_title,
t4.product_id,
t4.id AS link_id,
p1.name,
CONCAT_WS(" ", customers.first_name, customers.last_name, customers.group_name) AS customerName,
reservations.event_type
FROM reservations
LEFT JOIN customers ON reservations.customer_id = customers.id
LEFT JOIN
(SELECT *
FROM product_reservation AS t3
GROUP BY t3.reservation_id ) AS t4 ON t4.reservation_id = reservations.id
LEFT JOIN products AS p1 ON t4.product_id = p1.id
我可以将其放置为原始查询,但是会产生一个带有结果的数组-我需要能够创建一个查询对象,以便可以在结果上使用另一个模块。得到这个查询在laravel工作? 谢谢
是的,您可以使用雄辩的关系。 他们看起来像这样...
class Reservation extends Eloquent
{
public function products()
{
return $this->belongsToMany('Product');
}
}
class Product
{
public function reservations()
{
return $this->belongsToMany('Reservation');
}
}
$reservations = Reservation::with(array('products', function($q) {
$q->take(1);
}))->get();
foreach($reservations as $reservation) {
echo $reservation->name;
foreach($reservation->products as $product) {
echo $product->description;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.