关联表查询
数据库posts:
id | title | type |
---|---|---|
1 | 标题1 | 1 |
2 | 标题2 | 3 |
3 | 标题3 | 2 |
数据库class:
id | title |
---|---|
1 | 类型1 |
2 | 类型2 |
3 | 类型3 |
posts表的type对应class表的id;
我想查询结果是
[
'id'=>1,
'title'=>'标题1',
'type'=>1,
'type_title'=>'类型1' // 就是这个地方可以用posts表的type字段关联到class表的title字段
]
所以查询语句应该咋写?模型查询应该咋写?
我当前的办法是
$posts = posts::query()->where('id',1)->first();
$posts['type_title'] = class::query()->where('id',$posts['type_name'])->->first()['title'];
我觉得这样写好蠢;但是也不会高级的办法。请指教;
关联字段呢? type?
去看下关于模型关联的文档,你会找到答案的
Post 模型中
这样查询 Post 时就可以返回 type_title 这个字段了
模型关联一下就好 主要是你的数据库要按模型关联规则 type若是外键关联字段 要按 [外表_id] 也即是posts表里 type改为 class_id 然后对应Model 里面加上关联就好
如果直接要一维的结构,用DB查寻
用访问器吧,要用toArray()
$data=Posts::query()->where('id',1)->first()->toArray();
Posts模型里面,这种的问题就是你不要的时候,也会返回这个type_title字段出去
这样可以?
他这个是两个库吧?
为什么不用value()呢,在最后把first()换成value()