laravel实现一对多关联模型数据查询
本文我们就是要通过laravel的一对多的关联模型来快速实现数据的调用。
假如我们现在有两张表:user 和 posts,每个 user 可以拥有多个 posts,而每一篇 posts 只能属于一个 user,两者的关系是明显的一对多关系。
现在我们希望在获取某一篇 posts 的时候同时获取对应的 user 信息。
1、找到 users.php 模型文件,增加如下方法:
public function posts() { return $this->hasMany(Post::class); }
2、找到 posts.php 模型文件,增加如下方法:
public function author() { return $this->belongsTo(User::class); }
3、找到 BlogController.php 增加查询数据方法:
public function index() { $posts = Post::with('author')->get()->toArray(); echo '<pre>';print_r($posts); }
结果打印数据类似为:
<pre>Array ( [id] => 20 [uid] => 11 [type] => 2 [title] => "laravel实现一对多关联模型数据查询" [content] => "本文我们就是要通过laravel的一对多的关联模型来快速实现......" [ctime] => 1560422003 [utime] => 1560422003 [dtime] => [user] => Array ( [id] => 11 [name] => phpernote_admin [head_img_url] => http://www.phpernote.com/logo.pnng ) )
注意:
这实际上会执行下面两句 SQL 语句:
select * from `posts` select * from `users` where `users`.`id` in (<1>,<2>)
PHP之友评论