本文我们就是要通过laravel的一对多的关联模型来快速实现数据的调用。
假如我们现在有两张表:user 和 posts,每个 user 可以拥有多个 posts,而每一篇 posts 只能属于一个 user,两者的关系是明显的一对多关系。
user 表和 posts 表表结构如下:
CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` char(30) NOT NULL DEFAULT 'www.maopiaopiao.com' COMMENT '名称', `ctime` timestamp NULL DEFAULT NULL COMMENT '创建时间', `utime` timestamp NULL DEFAULT NULL COMMENT '更新时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; CREATE TABLE `posts` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) NOT NULL DEFAULT '1' COMMENT '用户表id', `title` char(30) NOT NULL DEFAULT '' COMMENT '标题', `content` text NOT NULL COMMENT '内容', `ctime` timestamp NULL DEFAULT NULL COMMENT '创建时间', `utime` timestamp NULL DEFAULT NULL COMMENT '更新时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='新闻表';
现在我们希望在获取某一篇 posts 的时候同时获取对应的 user 信息。
1、找到 users.php 模型文件,增加如下方法:
public function methodName() {
    //hasMany($related, $foreignKey = null, $localKey = null)
    //第一个参数为对应的model, 第二个参数默认为model对应的表的外键, 第三个参数默认为当前模型对应的表的主键
    return $this->hasMany(Post::class, 'user_id', 'id');
}
2、找到 posts.php 模型文件,增加如下方法:
public function methodUser() {
    //belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
    //第一个参数为model, 先讲第四个参数,默认为调用belongsTo()的方法名字, 第二个参数默认为第四个参数加上 '_id', 第三个参数默认为model的对应表的主键
    return $this->belongsTo(User::class, 'user_id', 'id');
}
3、找到 BlogController.php 增加查询数据方法:
public function index() {
    //with:类似于 SQL 中的 left join
    $posts = Post::with('methodUser')->get()->toArray();
    echo '<pre>';print_r($posts);
}
结果打印数据类似为:
<pre>Array
(
    [id] => 20
    [user_id] => 11
    [title] => "laravel实现一对多关联模型数据查询"
    [content] => "本文我们就是要通过laravel的一对多的关联模型来快速实现......"
    [ctime] => 1560422003
    [utime] => 1560422003
    [user] => Array
        (
            [id] => 11
            [name] => phpernote_admin
            [ctime] => 1560422003
            [utime] => 1560422003
        )
)
注意:
这实际上会执行下面两句 SQL 语句:
select * from `posts` select * from `user` where `user`.`id` in (<1>,<2>)