laravel:将多个(但只有一个相关项)mysql查询转换为laravel查询

时间:2014-10-24 11:55:43

标签: php mysql laravel eloquent

您好我将我正在处理的mysql查询转换为laravel eloquent查询并需要一些帮助。 我有一个保留表,链接到具有多对多关系的产品表。无论有多少产品与预订相关,我都想提取所有预订,而不是它找到的第一个产品。 这是我的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中工作? 谢谢

1 个答案:

答案 0 :(得分:0)

是的,你可以使用Eloquent关系。它们看起来像这样......

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;
    }
}