用户和地址关联关系 使用 hasMany 结果为地址全部被选出
user表结构
open_id(主键)
address表结构
address_id(主键) open_id (外键)
user模型
function addres(){
return $this->hasMany('App\Address','open_id','open_id')
}
Address模型
function owner(){
retrun $this->belongsTo('App\User','open_id')
}
bash$ php artisan tinker
App\user::first()->address;
执行结果:预期只第一个用户的地址,但是结果为整个address表中的数据
App\address::first()->owner;
执行正确
我故意修改open_id 为 不存在字段后,代码如下
return $this->hasMany('App\Address','open_idBCZ','open_id')
得到的报错结果显示
select * from `user_address` where `user_address`.`open_idBCZ` = 0 and `user_address`.`open_idBCZ` is not null
mysql中varchar字段和0比较 结果都为真,所以address表中的全部数据都复核条件。
由此可知在进行user表的查询的时候,得到的open_id为0,将0作为外键参数传给子查询,获得的结果就不是预期结果了。
请教,这个问题产生的原因,解决方法。
推荐文章: