thinkphp5 模型关联的bug

    xiaoxiao2021-03-25  100

    用tp5的模型关联时发现一个bug。为了输出关联模型的字段,有两种写法,一种是5.0.4以上版本才支持的bind(‘xxx’),另一个中是 field(‘xx’) bind写法如下

    public function images() { return $this->hasOne('FbPostImage','object_id', 'object_id')->bind('images'); } // 实例化时,获取数据,由于bind会绑定到父模型对象,不需要再手动指定 /** * 多个关联对象 */ public function testMultiPostImages() { $FbPostModel = new FbPost; $posts = $FbPostModel::all(function ($query) { $query->field('page_id,post_id,message,post_type,post_time_hk as publish_time,permalink_url as post_url, source, object_id') ->where('sync_status', 0)->order('update_time', 'desc'); }); $result = collection($posts)->hidden(['object_id'])->toArray(); return $result; }

    上述输出结果没有images。bind加上object_id也一样。没有输出images.。但是如果将$posts 遍历输出子post的images对象,是有值的。

    field写法如下

    public function images() { return $this->hasOne('FbPostImage','object_id', 'object_id')->field('images,object_id'); } /** * 多个关联对象 */ public function testMultiPostImages() { $FbPostModel = new FbPost; $posts = $FbPostModel::all(function ($query) { $query->field('page_id,post_id,message,post_type,post_time_hk as publish_time,permalink_url as post_url, source, object_id') ->where('sync_status', 0)->order('update_time', 'desc'); }, 'images'); $result = collection($posts)->hidden(['object_id'])->toArray(); return $result; }

    用field 写法,再手动指定输出关联模型输出field,可以输出images。 可能这个也是tp5的bug

    转载请注明原文地址: https://ju.6miu.com/read-13860.html

    最新回复(0)