入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

thinkphp5 模型关联的bug

创建时间:2017-03-09 投稿人: 浏览次数:1696

用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

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。