Laravel Eloquent with and find

后端 未结 4 1951
孤城傲影
孤城傲影 2020-12-30 18:54

Why is this not working?

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

I got a Array to String Conversion Exception.

But if i split t

相关标签:
4条回答
  • 2020-12-30 19:23

    Try:

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

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

    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.

    0 讨论(0)
  • 2020-12-30 19:25

    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');
    }
    
    0 讨论(0)
  • 2020-12-30 19:34

    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

    0 讨论(0)
  • 2020-12-30 19:48

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

    Article::whereIn('id', $ids)->with('category')->get();
    
    0 讨论(0)
提交回复
热议问题