Answer the question
In order to leave comments, you need to log in
How to make a selection from the database and set up relationships in Laravel?
Hello, I have a Region and Image model, respectively tables in the regions and images database. There is also an intermediate table image_region, because the relationship between Region and Image is many-to-many. One Region can have many images, and I have one common images table for the entire site. The problem is that when I edit the previously added Region, change the order of the pictures added to it, save. Then I open this Region for viewing, the order of the pictures remains the same, that is, it does not change. Although here in the intermediate table (image_region) I managed to make it so that the order of the records in it changes in accordance with the order of the pictures I set. But when fetching, as I understand it, there is still a request to the images table. And the fact that I have it in the intermediate table changes, it does not give any results. Please tell me how to make the order of the images change, I think that I probably need to change the order in the images table itself. Thank you in advance for your response.
The image request looks like this:
select `images`.*, `image_region`.`region_id` as `pivot_region_id`, `image_region`.`image_id` as `pivot_image_id` from `images` inner join `image_region` on `images`.`id` = `image_region`.`image_id` where `image_region`.`region_id` = 1
public function images()
{
return $this->belongsToMany('App\Image', 'image_region');
}
public function regions()
{
return $this->belongsToMany('App\Region');
}
Schema::create('image_region', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('region_id');
$table->foreign('region_id')->references('id')->on('regions');
$table->unsignedBigInteger('image_id');
$table->foreign('image_id')->references('id')->on('images');
});
Answer the question
In order to leave comments, you need to log in
You made a strange choice. Wouldn't it be better to create a field in image_region with a serial number?
UPD
what would happen
select `images`.*, `image_region`.`region_id` as `pivot_region_id`, `image_region`.`image_id` as `pivot_image_id` from `images` inner join `image_region` on `images`.`id` = `image_region`.`image_id` where `image_region`.`region_id` = 1 order by `image_region`.`id` ASC
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question