一对多关联
关联定义
一对多关联的情况也比较常见,使用hasMany方法定义,
参数包括:
hasMany('关联模型名','外键名','主键名',['模型别名定义']);
例如一篇文章可以有多个评论
<?php
namespace app\index\model;use think\Model;class Article extends Model {
public function comments()
{
return $this->hasMany('Comment');
}}
同样,也可以定义外键的名称
<?php
namespace app\index\model;use think\Model;class Article extends Model {
public function comments()
{
return $this->hasMany('Comment','art_id');
}}
如果需要指定查询字段,可以使用下面的方式:
<?php
namespace app\index\model;use think\Model;class Article extends Model {
public function comments()
{
return $this->hasMany('Comment')->field('id,author,content');
}}
关联查询
我们可以通过下面的方式获取关联数据
$article = Article::get(1);// 获取文章的所有评论dump($article->comments);// 也可以进行条件搜索dump($article->comments()->where('status',1)->select());
根据关联条件查询
可以根据关联条件来查询当前模型对象数据,例如:
// 查询评论超过3个的文章$list = Article::has('comments','>',3)->select();// 查询评论状态正常的文章$list = Article::hasWhere('comments',['status'=>1])->select();
V5.0.13+版本开始,hasWhere方法新增fields参数,用于指定返回的字段列表。例如:
// 查询评论状态正常的文章$list = Article::hasWhere('comments', ['status'=>1], 'name,title')
->select();
关联新增
$article = Article::find(1);// 增加一个关联数据$article->comments()->save(['content'=>'test']);// 批量增加关联数据$article->comments()->saveAll([ ['content'=>'thinkphp'], ['content'=>'onethink'],]);
定义相对的关联
要在 Comment 模型定义相对应的关联,可使用 belongsTo 方法:
<?php
name app\index\model;use think\Model;class Comment extends Model {
public function article()
{
return $this->belongsTo('article');
}}
根据字段排序
public function order(){
return $this->hasMany('Voter','activity_id')->order("vote_num asc");
}
根据字段随机排序
public function voter(){
return $this->hasMany('Voter','activity_id')->orderRaw("rand()");
}
- THE END -
最后修改:2021年1月7日