laravel5.2.9 - laravel5的模型关联问题
習慣沉默
習慣沉默 2017-05-16 16:49:37
[PHP讨论组]

我现在有三个表,分别如下

product表的字段为

product_id | product_name | type | price | category
type表的字段为

type_id  |  type_name
category表的字段为

category_id | category_name

现在是这样的关联方式

product中的type和category字段,分别对应type表的type_id和category表的category_id字段
请问怎么在模型中写关联啊,其实type和category字段关联其他两个表,就是为了能获取到type_name和category_name.

试了一晚上了,不知道是一对一还是一对多,愁死了,感谢朋友帮我解答下

習慣沉默
習慣沉默

全部回复(1)
阿神
class product extends Model {

    public function type()
    {
        // return $this->hasOne('App\type', 'foreign_key', 'local_key');
        return $this->hasOne('App\type', 'type_id', 'type');
    }
    public function category()
    {
        return $this->hasOne('App\category', 'category_id', 'category');
    }

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

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