php - laravel中数据库表得关联问题
迷茫
迷茫 2017-04-10 15:16:32
[PHP讨论组]

控制器中:

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(4)
高洛峰

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

class Phone extends Eloquent {

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

}
PHPz

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

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

高洛峰

请查看laravel的Eloquent ORM用法。

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

}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号