thinkphp5.0 模型关联 如何查询部分字段
2022-07-28 14:14:58
283
{{single.collect_count}}

模型

namespace app\common\model;
use think\Model;
class Order extends Model
{
public function goods(){
return $this->belongsTo(‘goods’,‘gid’,‘id’)->bind(‘goodsname’);
}
}

控制器

data=model ( ′orde r ′)−>with ( ′good s ′)−>field ( ′addtime,totalprice,ispay,status,hexiao,hexiaostatu s ′)−>order ( ′iddes c ′)−>where(data = model('order')->with('goods')->field('addtime,totalprice,ispay,status,hexiao,hexiaostatus')->order('id desc')->where( data=model(order)>with(goods)>field(addtime,totalprice,ispay,status,hexiao,hexiaostatus)>order(iddesc)>where(where)->select();
field这样写 查询的结果没有goodsname

data=model ( ′orde r ′)−>with ( ′good s ′)−>field ( ′addtime,totalprice,ispay,status,hexiao,hexiaostatus,goodsnam e ′)−>order ( ′iddes c ′)−>where(data = model('order')->with('goods')->field('addtime,totalprice,ispay,status,hexiao,hexiaostatus,goodsname')->order('id desc')->where( data=model(order)>with(goods)>field(addtime,totalprice,ispay,status,hexiao,hexiaostatus,goodsname)>order(iddesc)>where(where)->select();
data=model ( ′orde r ′)−>with ( ′good s ′)−>field ( ′gid,addtime,totalprice,ispay,status,hexiao,hexiaostatus,goodsnam e ′)−>order ( ′iddes c ′)−>where(data = model('order')->with('goods')->field('gid,addtime,totalprice,ispay,status,hexiao,hexiaostatus,goodsname')->order('id desc')->where( data=model(order)>with(goods)>field(gid,addtime,totalprice,ispay,status,hexiao,hexiaostatus,goodsname)>order(iddesc)>where(where)->select();
这两种field这样写 报错 Column not found: 1054 Unknown column ‘goodsname’ in ‘field list’ 查不到goodsname

正确的写法:
data=model ( ′orde r ′)−>field ( ′gid,addtime,totalprice,ispay,status,hexiao,hexiaostatu s ′)−>with ( ′good s ′)−>order ( ′iddes c ′)−>where(data = model('order')->field('gid,addtime,totalprice,ispay,status,hexiao,hexiaostatus')->with('goods')->order('id desc')->where( data=model(order)>field(gid,addtime,totalprice,ispay,status,hexiao,hexiaostatus)>with(goods)>order(iddesc)>where(where)->select();
也就是说:field 应在with关联预载入之前调用,并且要把关联的条件字段(gid)加进去,否则关联不上.

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}