Support the ongoing development of Laravel.io →
Eloquent Architecture
Last updated 2 years ago.
0

You need to use or lazy loading or eager loading. Hor if you want you can do another query when yo show a concrete item, depends on how you want to display it you will have diferent choices.

$posts = Post::where('id','<','10')->get();
        return Response::json($posts);

also, you can use:

$posts = Post::where('id','<','10')->with('author')->get();

$posts = Post::where('id','<','10')->get();
$posts->load('author);

"author" relationship must be defined in the POST model:

public function author()
{
return $this->belongsTo('Author','author_id');
}

and access from angular, using in the loop

 post.author.name

or if yoy have used the JOIN with author_name or the name you have given to that column

post.author_name

But I am thinking for large arrays in whereIn() (eager loading executes a second query using the id-s list of posts, like, whereIn('user_id',(1,2,3,4.....)) And I have read to some mysql professionals that we should try to avoid this type of queries, so, maybe, instead you can use "JOIN"

$posts = Post::select(DB::raw('posts.*,authors.name as author_name'))->where('id','<','10')->join('authors','posts.author_id','=','authors.id')->get() 

I put select to avoi "ambiguos id" ....you can rename as you want the columns,or what ever you want. And another little tip, to improve the space of the JSON, if you use select you can rename columns with 'a_n' instead 'author_name', that way if your JSON is quite large, your JSON will be lighter (also sometimes you will forget what you are displaying). You have a lot of choices depending what you are looking for, for example faster apps or speed....

I think you can use get(array('id','name'...), I think you can do similar things that are done with ->select()

Everithing is in the documentation and the API of laravel, just take a look.

The same thing for belongToMany, you can use eager loading, the you need to define relationship for that, and in angular loop you need to loop again for the relation items. Try using lazy loading. I think that should work. It's like in blade,

@foreach(posts as post) 
   @foreach(post->authors as $author)
       ......
   @endforeach 
@endforeach

I think is:

ng-repeat=authors in post.authors

but If you use join maybe you can use it the other way I have told you. It's true that that way you loss maybe the magis of the relationships that Eloquent give as.

I don't know if I helped you and sorry if my English level is bad.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.