目录
方法一:使用Eloquent ORM的with关联查询
在 ThinkPHP5 中,可以使用模型关联和条件查询来实现一对一关联查询。以下是一个示例:
假设有两个表,一个是 users 表,一个是 profiles 表。users 表中有一个 profile_id 字段,用于关联 profiles 表中的 id 字段。
首先,在 User 模型中定义一个 profile 方法,用于关联 Profile 模型:
// User.php
public function profile()
{
return $this->hasOne('Profile', 'id', 'profile_id');
}
然后,在控制器中使用模型关联查询,并添加条件:
// UserController.php
public function index()
{
// 查询 users 表中的所有记录
$users = User::with(['profile' => function($query) {
$query->where('address', 'like', '%北京%');
$query->field('profile_id,title');
}])
->where('status', '=', 1)
->field('id,nickname')
->select();
// 输出查询结果
foreach ($users as $user) {
if ($user->pro


被折叠的 条评论
为什么被折叠?



