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字段 为什么却可以查询出来结果?

laravel php-laravel php

残された亡き骸 9 years, 8 months ago

请查看laravel的Eloquent ORM用法。

Defining The Inverse Of A Relation

loli糖昔 answered 9 years, 8 months ago

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


 class Phone extends Eloquent {

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

}

asleep answered 9 years, 8 months ago

Your Answer