gpt4 book ai didi

php - Laravel 连接子查询

转载 作者:行者123 更新时间:2023-11-29 10:40:11 25 4
gpt4 key购买 nike

我有两个模型用户和地址,一个用户可以有多个地址,但我只想获取primary(其中primary=true)

这是我尝试过的,并且我在列表中获得了多个用户

$users = User::join('addresses', 'addresses.user_id', 'users.id')
->select('name','phone_number','address','landmark','city','state','pincode','users.status')
->get();

我也尝试过,但没有收到任何数据

$users = User::join('addresses', 'addresses.user_id', 'users.id')
->where('addresses.primary', true)
->select('name','phone_number','address','landmark','city','state','pincode','users.status')
->get();

谢谢

Collection {#375 ▼
#items: array:8 [▼
0 => User {#376 ▶}
1 => User {#377 ▼
#attributes: array:9 [▼
"name" => "Colin Sushanth"
"phone_number" => "9987217545"
"address" => "2nd Cross 3rd street, y this is my address"
"landmark" => "Near the address"
"city" => "Mangalore"
"state" => "Karnataka"
"pincode" => 575002
"status" => "valid"
"primary" => "true"
]
}
2 => User {#378 ▶}
]
}

最佳答案

你应该尝试这个:

$users = User::join('addresses', 'addresses.user_id', 'users.id')
->where('addresses.primary','=',1)
->select('name','phone_number','address','landmark','city','state','pincode','users.status')
->get();

或者:

$users = User::join('addresses', 'addresses.user_id', 'users.id')
->where('addresses.primary','=',true)
->select('name','phone_number','address','landmark','city','state','pincode','users.status')
->get();

更新答案

Blade 文件:

@if(isset($users))

@foreach($users as $user)

@if($user->primary === 'true')

//Your code

@endif

@endforeach

@endif

关于php - Laravel 连接子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45633277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com