簡體   English   中英

Laravel 4 Eloquent-在查詢生成器中使用/訪問ORM關系屬性

[英]Laravel 4 Eloquent - Utilize/Access ORM Relationship Properties in Query Builder

開始...

...讓我說,到目前為止,我希望ORM /雄辯的關系發揮100%的作用(在查詢生成器問題之外)。 我更改了一些命名約定以使示例更清楚,但否則代碼保持不變。

第一個示例工作正常。 第二個片段是我嘗試解釋自己在完成任務時遇到的困難。

一切正常。 使用$ filter_text查詢Person-> title

$people = Person::with('best_friend', 'associates')
    ->orderBy($order_by, $order_dir)
    ->where( function($query) use ($active, $filter_text) {
        $query->where('active', $active);
        if ($filter_text) {
            // This is working fine/expected
            $query->where('title', 'LIKE', "%$filter_text%");
        }
    })
    ->paginate(25);

使用閉包仔細查看我的where(function($ query))...

[...]
->where( function($query) use ($active, $filter_text) {
        $query->where('active', $active);
        if ($filter_text) {

            // This is working fine/expected
            $query->where('title', 'LIKE', "%$filter_text%");

            /**
             * I want to use the same $filter_text to query against the $person->best_friend->name field
             *     Something like this
             */
            $query->orWhere('best_friend.name', 'LIKE', "%$filter_text%");

        }
    })
[...]

這是我得到的錯誤

列未找到:SQLSTATE [42S22] 1054未知列'people.best_friend.name'在'where子句'(SQL:SELECT COUNT(*)從總people在哪里( active ?=和title ?LIKE或best_friendname LIKE ?))(綁定:數組(0 =>'1',1 =>'%g%',2 =>'%g',))

注意...

我嘗試了使用模型名稱,模型的ORM方法名稱和表名稱的幾種變體,並在復數/單數/大寫/等上使用了變體...它們似乎都返回了類似的錯誤。

*當在get()/ paginate()方法之后輸出/訪問結果時,所有“ best_friend”信息都可以訪問。* 我的問題歸結為如何在查詢構建器中訪問相同的數據。

任何見解/想法都將不勝感激。 我希望這個問題至少有意義。

在Twitter上找到我:@ErikOnTheWeb

如果我正確理解了,您想要的是在關系滿足特定條件時過濾主模型集合(人),因此:

Model::with($relations)->whereHas('onerelation', function($query)
{
    $query->where($onerelation_field, $operator, $value);
})
->where($model_field, $operator, $value)
->get();

這將返回一個Model的集合,該集合的關系Onerelation滿足指定條件(除了它們自己的條件之外)。

暫無
暫無

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

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