>  기사  >  백엔드 개발  >  laravel中数据库表得关联问题

laravel中数据库表得关联问题

WBOY
WBOY원래의
2016-06-06 20:39:081060검색

控制器中:

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

在post模板中:

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

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

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

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

回复内容:

控制器中:

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

在post模板中:

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

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

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

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

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

<code>class Phone extends Eloquent {

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

}
</code>

belongsTo()函数是 Laravel Eloquent 提供的模型间关系的一种,Post类由于继承了 \Eloquent 类所以也可以调用。

模型间关系具体该如何使用可以参考:深入理解 Laravel Eloquent(三)——模型间关系(关联)

请查看laravel的Eloquent ORM用法。

Defining The Inverse Of A Relation

<code>php</code><code>class 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);
    }

}
</code>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.