SoFunction
Updated on 2025-03-10

A brief analysis of the usability of the association of framework models such as Laravel

In early development, model associations brought great convenience. At the same time, it also improves database query efficiency (avoids duplicate queries, related explanations such as the n+1 query problem of laravel).

For example, in an interface that obtains user information, in addition to returning data from the user table, it also needs to return data from tables such as user_option or user_info. At this time, the form of model association using laravel is as follows:

class UserModel extends Model {
  protected $table = 'user';
  public $timestamps = false;
  
  public function userOption()
  {
    return $this->hasOne(UserOptionModel::class , 'user_id' , 'id');
  }
  
  public function findById(int $user_id)
  {
    $res = self::with(['user_option'])
      ->find($user_id);
    return $res;
  }
}

class UserOptionModel extends Model {
  protected $table = 'user_option';
  public $timestamps = false;
}

Judging from the above code, model association is quite convenient to use!

However, when the number of users in your system increases in the later stage, it is inevitable to use caches like redis. If the user table needs to be cached, the result may be another scenario.

class UserCache {
  // Get user information  public static function findById(int $user_id)
  {
    // Get cached data    $user = Redis::string('user_' . $user_id);
    if (!empty($user)) {
      return $user;
    }
    $res = UserModel::findById($user_id);
    Redis::string('user_' . $user_id , $res);
    return $res;
  }
}

The above code caches the user's information to redis. If the user's user table body information has not changed, but the user_option table has changed, then the user's redis cache should be deleted normally.

In this case, the complexity of the code will rise sharply!

Therefore, I personally recommend that you do not use model association during code development!

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.