Hey guys, i've been looking for example about dynamic constraints using eager loading, but many examples just give a static constraints. Consider i have two models, Post and User : Post model :
<?php
class Post extends Eloquent {
public function user() {
return $this->belongsTo('User','post_author');
}
}
User model :
<?php
class User extends Eloquent {
public function posts() {
return $this->hasMany('Post','post_author');
}
}
in my router, i have this code :
Route::get('test/{usern}','PostController@testAction');
here is my controller :
public function testAction($usern) {
$post= Post::with(array('user' => function($query) use ($usern)
{
$query->where('username', '=', $usern);
}))->get();
return View::make('post.postbyuser')->with('post', $post);
}
and here is my view :
@foreach($post as $posts)
{{ $posts->post_body }}
@endforeach
in raw mysql, what i want to achieve is something like this :
select p.post_title,p.post_body,u.username from post p inner join user u on p.post_author=u.id_user where u.username="admin"
any ideas why my code above won't work??, the return values is displaying the post without filtering them based on username which i passed from router, and also when i'm trying to get the user data in view with this code :
@foreach($post as $posts)
{{ $posts->post_body }}
{{ $posts->user->username }}
@endforeach
it's throwing me an error, i think i've already create the relationship between those tables, so i can access it using code above, thought it will be the same thing when i'm using this controller :
$post = Post::with('user','comments')->orderBy('updated_at', 'desc')->paginate(5);
with controller above, i can easily access the user data using :
{{ $post->user->username }}
why when i'm using eager loading constraints it has different result?? Thanks.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community