【问题标题】:Filtering query with Laravel's Eloquent ORM使用 Laravel 的 Eloquent ORM 过滤查询
【发布时间】:2014-08-12 06:59:38
【问题描述】:

我已经定义了这样的 Eloquent 模型:

class Order extends Eloquent {
    public function station() {
        return $this->belongsTo('Station');
    }
}

class Station extends Eloquent {
    public function client() {
        return $this->belongsTo('Client');
    }

    public function orders() {
        return $this->hasMany('Order');
    }
}

class Client extends Eloquent {
    public function stations() {
        return $this->hasMany('Station');
    }
}

现在我想做一个与所有这些相关的查询,但我无法弄清楚如何以 Eloquent 方式进行。这是我要返回的查询的 SQL:

SELECT o.id, c.name AS cname, s.name AS sname, o.created, o.due, o.name, o.comments, o.points
FROM orders o
JOIN station s ON o.station_id = s.id
JOIN client c ON c.id = s.client_id
WHERE s.id IN (
    SELECT id FROM orders WHERE complete
)

我对如何以 Laravel/Eloquent 方式做到这一点感到困惑。

【问题讨论】:

  • 您需要什么结果?雄辩的模型或那些selected 字段的数组?你也确定:WHERE s.id IN ... - 不是o.id IN... 吗?您可以使用 Query\Builder 构建完全相同的查询,不需要原始部分。

标签: laravel-4 eloquent


【解决方案1】:

嗯,这里有几种处理方法。

  1. 执行整个原始查询
  2. 进行有说服力的查询

为了更好地控制第一点我会得到的查询

这可以通过直接执行语句来实现

DB::select(DB::raw($your_sql_here));

或通过查询构造函数构建。

第二种方法涉及对关系如何运作的一些研究。 最终查询可能如下所示(不准确,但会给您提示):

Order::with('station.client')->whereIn('station.id', DB::raw('SELECT id FROM orders WHERE complete'))

希望这会有所帮助。还有一个很棒的 cheet-sheet 可以为您提供更多关于 DB 和 Model 对象的方法。

【讨论】:

    【解决方案2】:

    你应该可以使用Eager Loading

    $orders = Order::where('complete', $complete)->with('station.client')->get();
    

    然后你可以遍历每个订单:

    foreach ($orders as $order) {
    
        echo e("The order ID is $order->id <br>");
        echo e("The station ID is {$order->station->id} <br>");
        echo e("The client ID is {$order->station->client->id} <br>");
    }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 2015-12-06
      • 1970-01-01
      • 2016-06-13
      • 2015-05-16
      相关资源
      最近更新 更多