gpt4 book ai didi

php - 如何在 Laravel 和 Eager load 关系中将多个单独的 eloquent 模型组合为一个模型

转载 作者:行者123 更新时间:2023-11-29 20:58:40 26 4
gpt4 key购买 nike

我有许多单独的模型,我想将它们全部组合起来以利用热切加载的优势。

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

这里要记住的重要一点是,eloquent 还包含查询构建器的所有功能。在大多数情况下,它比完整的 SQL 查询更容易阅读和维护。

阅读 Material :

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

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

关于php - 如何在 Laravel 和 Eager load 关系中将多个单独的 eloquent 模型组合为一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37413030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com