Skip to content

Início / Optitravel / Models

hasMany(string $relatedModel, string $foreignKey, string $localKey = 'id')

The hasMany() method defines a one-to-many relationship between two models. It retrieves all related records from another table where the foreign key matches the value of the current model's local key.

This is typically used when one record in the current model owns or is associated with multiple records in the related model.

Parameters

  • string $relatedModel – The name of the related model class (e.g., 'User' if referring to App\Models\User).

  • string $foreignKey – The column name in the related model’s table that references the current model.

  • string $localKey (optional) – The column name in the current model used to match the foreign key. Defaults to 'id'.

Returns

  • An array of related model objects, or an empty array if no matches are found or the local key is not set.

Example

use \App\Models\UserGroup;

$userGroupModel = new UserGroup();
$group = $userGroupModel->find($params['id'])->with(['members']);

foreach ($group->members as $member) {
    echo $member->name . '<br>';
}

Notes

  • The related model must be under the App\Models namespace.

  • The method uses a SQL SELECT query with a WHERE clause based on the $foreignKey.

  • Each result row is mapped into a separate object instance of the related model.

  • If the $localKey is not set on the current object, the method returns an empty array.

  • Useful for relationships like: Group → Users, Category → Products, Author → Posts.

Behavior

  • Instantiates the related model class dynamically.

  • Uses the current object’s local key value to filter the related records.

  • Maps each result row to an object using mapResultToObject().

  • Returns all matching related records as an array of model instances.


(Última atualização: 13/05/2025)