
thinkphp6 中使用 with() 关联查询并扁平化二维数组
在 thinkphp6 中,使用 with() 方法可以关联查询多个模型数据。如果关联模型存在多对一关联关系,查询结果将返回一个二维数组,包含父模型和子模型的数据。
然而,有时我们希望将二维数组扁平化,类似于 sql 中的 join 查询。为此,我们可以使用 bindattrs() 方法,将子模型的属性绑定到父模型。
具体步骤如下:
立即学习“PHP免费学习笔记(深入)”;
考虑以下示例,card 表与 profile 表通过一对一关联关系关联:
public static function get_card_store_list()
{
return self::with(['profile'])
->select()
->appendto('profile')
->toarray();
}这将返回一个二维数组,包含 card 表和 profile 表的数据:
[
{
"id": 1,
"times": 10,
"add_time": 1626933885
}
]如果我们希望将数组扁平化,我们可以使用 bindattrs() 方法:
return self::with(['profile'])
->select()
->bindattrs('profile')
->toarray();这将返回一个一维数组,包含 card 表和 profile 表的所有数据:
[
{
"id": 1,
"times": 10,
"add_time": 1626933885
}
]通过使用 bindattrs() 方法,我们可以轻松地扁平化模型关联查询的结果,消除非别名冲突,并获取类似于 sql join 查询的单维数组。
以上就是ThinkPHP6 中如何使用 with() 关联查询并扁平化二维数组?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号