laravel5的模型关联问题

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

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.

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

阅读 2.4k
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();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进