laravel5.2.9 - laravel5的模型关联问题
本文介绍了laravel5.2.9 - 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.
试了一晚上了,不知道是一对一还是一对多,愁死了,感谢朋友帮我解答下
解决方案
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();
这篇关于laravel5.2.9 - laravel5的模型关联问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文