ThinkPHP5.1 join两表或者多表查询

版权声明:段子与短视频鸦片看多了,人就会失去长文阅读能力,智商也会变低,办事能力也会变弱,也会失去秋收起义般的大痣 ,反而性格变得爆裂 —— 鲁迅。 https://blog.csdn.net/weixin_41827162/article/details/85062006

-

表1为lj_product_item左表a,

表2 lj_prodyct_class右表b,

表a有表b的id,

将表a中的表b  id所对应的中文名查询出来,

最后显示在一个结果集里面。

-

注意,where、field、order需要指定a和b,如果有重复字段名,可能会报错,写法a.xx、b.xx。

-

   /*
     * 商品名
     * */
    public function list_product_item(){

        $product_item_id = input('id');

        if ($product_item_id === 'all'){
            $res = DB::name('lj_product_item')->alias('a')->leftJoin([
                ['lj_product_class b', 'a.product_class_id=b.product_class_id'],
            ])->field('a.product_item_id, a.product_item_name, a.product_item_onlycode, a.create_time, a.update_time, a.order, b.product_class_name, b.product_class_onlycode')->order('a.order desc')->select();
        }else{
            $res = DB::name('lj_product_item')->where('product_item_id', $product_item_id)->alias('a')->leftJoin([
                ['lj_product_class b', 'a.product_class_id=b.product_class_id'],
            ])->field('a.product_item_id, a.product_item_name, a.product_item_onlycode, a.create_time, a.update_time, a.order, b.product_class_name, b.product_class_onlycode')->find();
        }

        $state = 1;
        $msg = '商品名请求成功';
        $content = $res;

        $back = [
            'state'=>$state,
            'msg'=>$msg,
            'content'=>$content,
        ];

        return json_encode($back, JSON_UNESCAPED_UNICODE);
    }

-

更多写法可参考https://www.cnblogs.com/Renyi-Fan/p/8991048.html

扫描二维码关注公众号,回复: 4983964 查看本文章

-

猜你喜欢

转载自blog.csdn.net/weixin_41827162/article/details/85062006
今日推荐