简体   繁体   English

如何在Laravel和Eager负载关系中将多个个体雄辩模型合并为一个模型

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

I have many individual models and I want to combine them all to take advantage of eagerloading. 我有很多单独的模型,我想将它们全部结合起来以利用预先加载的优势。

$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');

I get the following error 我收到以下错误

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

What is the solution? 解决办法是什么?

$all is an array. $ all是一个数组。 Array is not an object. 数组不是对象。 So when you call $all->with(), you get an error "Trying to get property of non-object". 因此,当您调用$ all-> with()时,会出现错误“试图获取非对象的属性”。 Pretty straightforward :). 非常简单:)。

Your code seems to be needlessly convoluted. 您的代码似乎不必要地复杂。 You query is not too hard to do in Eloquent and Query Builder. 在Eloquent和Query Builder中查询不是很困难。 Read a bit of documentation and start using its awesome features instead of hacking your way around that :). 阅读一些文档,并开始使用其出色的功能,而不用自己动手:)。

You code could be replaced with this much more readable snippet (or something like this): 您的代码可以替换为更具可读性的代码段(或类似的代码):

$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();

The important thing to remember here is that eloquent also packs all the power of query builder. 这里要记住的重要一点是,雄辩的语言还包含了查询生成器的所有功能。 In most cases it will be easier to read and maintain than full SQL queries. 在大多数情况下,它比完整的SQL查询更易于阅读和维护。

Reading material: 阅读材料:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM