laravel中数据库表得关联问题

控制器中:

public getShow($id){
$post=Post::find($id)
return View::make('admin.post-detail')->with('posts',$post);
}

在post模板中:

public function user(){
            return $this->belongsTo('User');
}

然后在post-detail.blade.php中可以这样使用:$post->user ..

@foreach($posts as $post)
{{$post->user->username}}
@endforeach

而posts表中并没有user字段 为什么却可以查询出来结果?

阅读 7.6k
4 个回答

会在post表中找user_id字段,如果您想定义一个不同的外键字段,您可以通过 belongsTo 函数的第二个参数传递它:

class Phone extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User', 'local_key');
    }

}
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);
    }

}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题