In some cases you may have a default or a primary row with a one to many
relationship. Which is determined by a column like primary
. And if you change the primary row you would set the one you want to 1
and the others to 0
;
Here's an example showing my approach to how I solved this using Yii2
.
Ex: we have two tables User
and UserAddress
This is a function in the UserAddress
class. It's job is to make the current UserAddress
as the primary address for the User
.
public function makePrimary() {
$addresses = $this -> getUser() -> getUserAddresses() -> all();
foreach ( $addresses As $address ) {
$address -> is_primary = 0;
$address -> save();
}
$this -> is_primary = 1;
$this -> save();
}
Now my question, is this a good approach, that you normally do? If not, can you suggest a better approach to achieve the same result?
With your approach the performance takes a big hit as more the number of address rows, more the load on the server.
Consider you have 50 address rows for one user. As per your code the query execution is as follows
So in total the MySQL database queried for about 53 times.
But consider the following approach. I'm assuming that getUser() is related to getUserAddresses() via "user_id" and the name of the address table is "user_addresses"
Here you can update is_primary as 0 for all the rows using one update query. So in total you just used 2 queries to perform the task