The problem of the usage of laravel's model

I think belongsTo or hasMany is usually written in model. What"s the use of writing this? The following is the code in someone else"s Car model. I think when he used it in the controller, he wrote $car = Car::find ($id) . It doesn"t seem to be convenient, for example, to write DB::table ("car") directly. Why do you write belongsTo and hasMany in the model?

public function user()
{
   return $this->belongsTo(User::class);
}
Feb.28,2021

the benefits of using models and model relationships are:

  1. once relationships are defined, they are available everywhere. If the database is not named properly, when you go to join , you have to care whether the foreign key of join is called xx_id or id
  2. .
  3. is easier to read than join . And the relationship can be connected all the time, such as $order- > user- > userAddress- > province- > name , and if you use join , you will get join three tables.
  4. it is easy to decouple with the model. The model has events such as creating , updating , and deleting . For example, when a user needs to send a text message to the user when placing an order, you can listen to the created event of order to encode, without putting the SMS code in the code for creating the order. For another example, adding commodity categories requires a log function, but there are multiple entries for adding categories. For example, when adding goods, you can enter a new category and add categories at the same time, or you can add categories separately in category management. The codes for adding categories for both entries are Category::create ([xx]) . If you want to write a log, you only need to write in one place to use the model listener. can learn . But if he uses DB::table ()-> insert , it is impossible to modify only one place to complete this function.
for example, in order to query the user's nickname, the user controller needs to introduce the data model first. Use AppModelsData; is not as good as DB::table ('data')-> where (' uid',$uid)-> get ().

you can't just consider the controller in front of you. If there is an order, that saves a user_id, to output user_name, to define the relationship, then you can directly $order- > user- > user_name . If there is a user address, user discount, user xxx, every join does not feel troublesome. No, no, no.


public function user()
{
   return $this->belongsTo(User::class, 'id', 'uid');
}

if you write it this way, it means that the id in your car table is associated with the uid in the user table, and then you can use it like this directly when you use it.

$car = Car::find($id)->with('user')->get();

in this way, you are tantamount to looking up the data of the two tables. For details, you can take a look at laravel's orm

.
Menu