[英]How can i get query result id in controller from Laravel?
I want to take houses lists and houses pictures on mysql from laravel. 我想在laravel上获取房屋清单并在mysql上放置房屋图片。 But, i have this problem.
但是,我有这个问题。 Using the process below:
使用以下过程:
$houses = Houses::query()
->orderBy('sort', 'ASC')
->take('6')
->get();
This query, give houses list to me. 这个查询,给我房屋清单。 And I need to use the houses I retrieve to get their photos, this is the best I could think of:
而且,我需要使用检索到的房屋来获取照片,这是我能想到的最好的方法:
$pictures = Housephotos::query()
->where('house_id', '=', $houses->house_id)
->get();
Question one: This process is correct? 问题一:这个过程正确吗?
Question two : How can do this? 问题二:怎么办?
You need to make a relationship between Housephotos
and House
so that there is house_id in Housephotos. 您需要在
Housephotos
和House
之间Housephotos
关系,以便Housephotos中有house_id。 If this is true, you can already use the houses Id you have to retrieve the houses Id: 如果是这样,则您已经可以使用房屋ID来检索房屋ID:
Say you already have the houses, then you can have: 假设您已经拥有房屋,则可以拥有:
$pictures = Housephotos::whereIn('house_id', '=', $houses->pluck('id')->toArray())
->get();
This will give you the houses photos. 这会给你房子的照片。
Add a relation to Houses: 为房屋添加关系:
class Houses extends Model
{
public function photos()
{
return $this->hasMany(Housephotos::class);
}
}
and now you can get the photos easily like: 现在您可以轻松获取照片,例如:
$houses = Houses::query()
->orderBy('sort', 'ASC')
->take('6')
->get();
foreach ($houses->photos as $photo) {
echo $photo->id;
}
the problem with that is, select query will run n times (5 times for this example). 问题在于,select查询将运行n次(此示例为5次)。
if you add with
to the query however, then laravel will run a single in
query to get the pictures: 但是,如果将
with
添加到查询中,则laravel将运行单个in
查询以获取图片:
$houses = Houses::query()
->with('pictures')
->orderBy('sort', 'ASC')
->take('6')
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.