In the controller:
public getShow($id){$post=Post::find($id)return View::make('admin.post-detail')->with('posts',$post);}
In the post template:
public function user(){ return $this->belongsTo('User');}
You can then use this in post-detail.blade.php: $post->user.
@foreach($posts as $post){{$post->user->username}}@endforeach
And there is no user field in the posts table. Why can I query the results?
Reply content:
In the controller:
public getShow($id){$post=Post::find($id)return View::make('admin.post-detail')->with('posts',$post);}
In the post template:
public function user(){ return $this->belongsTo('User');}
You can then use this in post-detail.blade.php: $post->user.
@foreach($posts as $post){{$post->user->username}}@endforeach
And there is no user field in the posts table. Why can I query the results?
The user_id field is found in the post table, and if you want to define a different foreign key field, you can pass it through the second parameter of the Belongsto function:
class Phone extends Eloquent { public function user() { return $this->belongsTo('User', 'local_key'); }}
belongsTo()A function is one of the relationships between models provided by Laravel eloquent, and Post classes \Eloquent can also be called because they inherit the class.
The relationship between models can be used as a reference: in-depth understanding of Laravel eloquent (iii)--Model Relationship (association)
See the eloquent ORM usage of laravel.
Defining the inverse of A Relation
phpclass Post extends Eloquent { public function user() { //$foreignKey默认为当前调用函数_id,即user_id,$otherKey为当前类主键id //select user_id from post where id=$post_id; //select username from user where user_id=$user_id; return $this->belongsTo('User', $foreignKey, $otherKey); }}