关联表查询

数据库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'];

我觉得这样写好蠢;但是也不会高级的办法。请指教;

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 9

关联字段呢? type?

4年前 评论
hackxiaoya (楼主) 4年前
hackxiaoya (楼主) 4年前

去看下关于模型关联的文档,你会找到答案的

4年前 评论

Post 模型中

   public function typeCategory()
    {
        return $this->belongsTo(Class::class,'type','id')->withDefault(['title'=>'暂无']);
    }

    public function getTypeTitleAttribute()
    {
        return $this->typeCategory->title;
    }

这样查询 Post 时就可以返回 type_title 这个字段了

4年前 评论
hackxiaoya (楼主) 4年前
GeorgeKing 4年前
playmaker

模型关联一下就好 主要是你的数据库要按模型关联规则 type若是外键关联字段 要按 [外表_id] 也即是posts表里 type改为 class_id 然后对应Model 里面加上关联就好

4年前 评论

如果直接要一维的结构,用DB查寻

DB::table('posts')->select(['posts.*', 'class.title as type_title'])->where('posts.id', 1)->leftJoin('class', 'posts.type', '=', 'class.id')->get();
4年前 评论
hackxiaoya (楼主) 4年前
GeorgeKing (作者) 4年前

用访问器吧,要用toArray()
$data=Posts::query()->where('id',1)->first()->toArray();

Posts模型里面,这种的问题就是你不要的时候,也会返回这个type_title字段出去


protected $appends = ['type_title'];

public function getTypeTitleAttribute()
    {
        if (isset($this->type)) {
            return Class::where('id',$this->type)->value('title')?:'不存在';
        } else {
            return  '不存在';
        }
    }
4年前 评论
GeorgeKing 4年前
小猪蹄子 (作者) 4年前
GeorgeKing 4年前
小猪蹄子 (作者) 4年前

这样可以?

Post::from('posts AS p')
    ->leftJoin('class AS c', 'p.type', '=', 'c.id')
    ->select('p.id','p.title','p.type','c.title AS type_title')
    ->where('p.id',1)
    ->get();
4年前 评论

他这个是两个库吧?

4年前 评论
小猪蹄子 4年前
Tangqy (作者) 4年前
hackxiaoya (楼主) 4年前

为什么不用value()呢,在最后把first()换成value()

4年前 评论
hackxiaoya (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!