[top-think/think]模型一对多关系,多的表with一的表,如果多的这边关联id为null然后find时会报错

2023-12-18 826 views
5

版本:5.1

模型一对多关系,多的表with一的表,如果多的这边关联id为null然后find时会报错,看了一下出错的SQL为:

SELECT * FROM `ca_major_line` WHERE (  `id` =  ) AND `ca_major_line`.`delete_time` IS NULL

id没有拼进去,这里应该是IS NULL才对

附上两个模型,还有查询代码:


/**
 * Class Department
 * @package app\common\model
 * @property int id
 * @property int comp_id
 * @property int major_id
 * @property string name
 * @property int sort
 * @property string delete_time
 * @property string create_time
 * @property string update_time
 */
class Department extends BaseModel {
    public function majorLine() {
        return $this->belongsTo('MajorLine', 'major_id', 'id');
    }
}

/**
 * Class MajorLine
 * @package app\common\model
 * @property int id
 * @property string name
 * @property string delete_time
 * @property string create_time
 * @property string update_time
 */
class MajorLine extends BaseModel {

    public function department() {
        return $this->hasMany('Department', 'major_id', 'id');
    }
}

$dept = Department::with(['majorLine'])->where('id', 1)->find();

回答

9

什么情况下关联id为null 数据怎么写入的 难道不是肯定属于某个MajorLine么?

3

比如一个商品可能属于一个类别,也可以没有类别,没有类别的时候商品的类别ID就是NULL

4

用 all 不会报错,现在的解决办法是:

$dept = Department::with(['majorLine'])->where('id', 1)->limit(1)->all();
if (count($dept) <= 0)
    exception('部门不存在');
return $dept[0];
5

我改进了下

5

多谢