Laravel Eloquent with 和 find

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16864010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:28:09  来源:igfitidea点击:

Laravel Eloquent with and find

laraveleloquent

提问by Marco

Why is this not working?

为什么这不起作用?

Article::with('category')->find($ids)

I got a Array to String Conversion Exception.

我有一个数组到字符串转换异常。

But if i split the query into 2 parts like this:

但是,如果我将查询分成这样的两部分:

$articles = Article::with('category')

and

$articles = $articles->find($ids)

I didn't get any exception and the result is right.

我没有得到任何异常,结果是正确的。

采纳答案by dani24

Just for the posterity... other way you can do this is:

只是为了后代......你可以这样做的另一种方式是:

Article::with('category')->whereIn('id', $ids)->get();

This should be better (more performant), because it's leaving the query to the database manager

这应该更好(性能更高),因为它将查询留给数据库管理器

回答by Half Crazed

Try:

尝试:

Article::with('category')->get()->find($ids);

You need to get the articles first before you can call find() I believe.

我相信,您需要先获取文章,然后才能调用 find()。

Warning: This retrieves every single article from the database and loads them all into memory, and then selects just one from all that data and returns it. That is probably not how you would want to handle this problem.

警告:这将从数据库中检索每篇文章并将它们全部加载到内存中,然后从所有数据中仅选择一篇并返回它。这可能不是您想要处理此问题的方式。

回答by Adam

This will give you the results based on an array of IDs in Laravel 4

这将根据 Laravel 4 中的一组 ID 为您提供结果

Article::whereIn('id', $ids)->with('category')->get();

回答by S1lllver

Create object and set his properties with relationships

创建对象并使用关系设置其属性

for example, code in your Controller or Service

例如,您的控制器或服务中的代码

$article = new Article;
$article = $article->find($id);

$result->article = $article;
$result->article->category = $article->category;

return response()->json($result);

Code in your Model

模型中的代码

public function category() {
    return $this->hasOne('App\Category');
}