thinkphp关联的一些查询如hasWhere怎么用or查询


注意:本例子都以衣服表和衣服sku表为例。

(衣服表:衣服的基本信息;衣服sku表:衣服不同规格的排列组合。易理解是说法,有款夹克衣服,那它的基本信息存衣服表,它不同尺寸和颜色排列组合得到的衣服信息存到衣服sku表)

 

1.场景一:通过衣服名称搜索衣服基本信息

  这个显然是单模型搜索如

$where[] = ['goods_name','like','%'.$keywords.'%'];//模型中写了搜索器的,直接写成数组key=>value形式
GoodsModel::where($where);

2.场景二:查询sku表的所有信息,并且关联衣服基本信息

  其实就是查出sku表但是关联一下主表(因为也要显示主表的一些信息)

//1.在GoodsSukModel中建立与GoodsModel一对一的关系 (如果goods到GoodsSuk关联就是一对多了)
    /**
     * 一对一关联
     * @return \think\model\relation\HasOne
     */
    public function goods()
    {
        //bind是把查出来的对象中指定字段取出来
        return $this->hasOne(GoodsModel::class, 'id', 'goods_id')->where('is_del', 0)->bind(['goods_name','spu']);
    }


//2.GoodsSukDAO中的调用
$with = ['goods'];
GoodsSukModel::where()->with($with)

3.场景三:因为现在衣服sku是主模型,可通过颜色尺寸查询sku信息

$where[] = ['size','=','xl'];
$with = ['goods'];
GoodsSukModel::where($where)->with($with)

 

4.场景四:如果上面的搜索功能想増加即按照主模型(GoodsSukModel)字段搜索,也能按照关联模型衣服表的名称搜索

$where[] = ['size','=','xl'];
$hasWhere[] = ['goods_name','like','%夹克%']; //模型中写了搜索器的,直接写成数组key=>value形式
$with = ['goods']; GoodsSukModel::where($where)->hasWhere('goods',$hasWhere )->with($with)

参考 : https://www.kancloud.cn/manual/thinkphp6_0/1037600

 

 

5.场景五:我们知道在主模型(GoodsSukModel)搜索有 where和whereOr,但是关联模型的搜索默认是and,怎么用or呢?

    我们想按照,衣服表中的goods_name和衣服的款号搜索,只要任意匹配到都行?

        $with = ['goods'];
        $field = [];
        $res = $this->getModel()->hasWhere('goods',function($query)use($keywords){
            $query->where('goods_name', 'like', '%'.$keywords.'%')->whereOr('spu', 'like', '%'.$keywords.'%');
        })->with($with)->whereOr('size','xl')->field($field)->paginate($size)->toArray();

也可以不用闭包,用下面的返回$where对象 

参考(最下面):https://www.kancloud.cn/manual/thinkphp6_0/1037602

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM