簡體   English   中英

如何在Laravel和Eager負載關系中將多個個體雄辯模型合並為一個模型

[英]How to combine multiple individual eloquent models as one in Laravel and Eager load relation

我有很多單獨的模型,我想將它們全部結合起來以利用預先加載的優勢。

$match_query = "select * from feeds " .
                "WHERE (user_id IN ($users_size)) " .
                "OR (target_id IN ($slugs_size) AND feedable_type = 'review') " .
                "ORDER BY created_at DESC LIMIT 5;";

//Query works fine and return 2 results 
$results = DB::select($match_query, $consolidatedArray);

    //to convert returned php standard obj to array
    $results = json_decode(json_encode($results), True);

    $all = [];

    foreach($results as $result){
        $x = new \App\Feed($result);

        //I am able to get relation like this for single item
        // $x->user;

        $all[] =  $x;
    }

    //but this thing is not working (i am trying to eager load)
    $data = $all->with('user');

我收到以下錯誤

ErrorException in FeedsRepository.php line 67:
Trying to get property of non-object

解決辦法是什么?

$ all是一個數組。 數組不是對象。 因此,當您調用$ all-> with()時,會出現錯誤“試圖獲取非對象的屬性”。 非常簡單:)。

您的代碼似乎不必要地復雜。 在Eloquent和Query Builder中查詢不是很困難。 閱讀一些文檔,並開始使用其出色的功能,而不用自己動手:)。

您的代碼可以替換為更具可讀性的代碼段(或類似的代碼):

$results = Feed::whereIn('user_id', $users_size)
            ->orWhere(function($q) use($slugs_size) {
                $q->whereIn('target_id', $slugs_size)->orWhere('feedable_type', 'review');
            })
            ->with('user')
            ->orderBy('created_at', 'desc')->take(5)->get();

這里要記住的重要一點是,雄辯的語言還包含了查詢生成器的所有功能。 在大多數情況下,它比完整的SQL查詢更易於閱讀和維護。

閱讀材料:

https://laravel.com/docs/master/eloquent

https://laravel.com/docs/master/queries

暫無
暫無

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

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