thinkphp5.0 模型关联 如何查询部分字段

模型

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

控制器

d a t a = m o d e l ( ′ o r d e r ′ ) − > w i t h ( ′ g o o d s ′ ) − > f i e l d ( ′ a d d t i m e , t o t a l p r i c e , i s p a y , s t a t u s , h e x i a o , h e x i a o s t a t u s ′ ) − > o r d e r ( ′ i d d e s c ′ ) − > w h e r e ( 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

d a t a = m o d e l ( ′ o r d e r ′ ) − > w i t h ( ′ g o o d s ′ ) − > f i e l d ( ′ a d d t i m e , t o t a l p r i c e , i s p a y , s t a t u s , h e x i a o , h e x i a o s t a t u s , g o o d s n a m e ′ ) − > o r d e r ( ′ i d d e s c ′ ) − > w h e r e ( 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();
d a t a = m o d e l ( ′ o r d e r ′ ) − > w i t h ( ′ g o o d s ′ ) − > f i e l d ( ′ g i d , a d d t i m e , t o t a l p r i c e , i s p a y , s t a t u s , h e x i a o , h e x i a o s t a t u s , g o o d s n a m e ′ ) − > o r d e r ( ′ i d d e s c ′ ) − > w h e r e ( 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

正确的写法:
d a t a = m o d e l ( ′ o r d e r ′ ) − > f i e l d ( ′ g i d , a d d t i m e , t o t a l p r i c e , i s p a y , s t a t u s , h e x i a o , h e x i a o s t a t u s ′ ) − > w i t h ( ′ g o o d s ′ ) − > o r d e r ( ′ i d d e s c ′ ) − > w h e r e ( 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)加进去,否则关联不上.

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值