laravel原生DB连表查询

1.现有2张表 文章表,作者表

1.2数据解构DDL

CREATE TABLE `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `article_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '文章',
  `author_id` int(255) DEFAULT NULL COMMENT '外键',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='文章表';
CREATE TABLE `author` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `author_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '作者',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='作者表';

2.控制器代码:

查询文章的id与文章的名称和作者

$data=\DB::table('article as t1')->select('t1.id','t1.article_name','t2.author_name')->leftJoin('author as t2','t2.id','=','t1.author_id')->get();
     return dd($data);

2.1打印显示结果如下:

posted @ 2020-05-03 13:09  以己为镜  阅读(1353)  评论(0编辑  收藏  举报