Skip to content

Início / Optitravel / Models

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

The hasOne() method defines a one-to-one relationship between two models, where the current model "owns" exactly one related record in another table.

It automatically performs a query using the local key of the current model and the foreign key of the related model to fetch a single matching record.

Parameters

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

  • 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 instance of the related model if a match is found.
  • null if no matching record is found or the local key is missing

Example

use \App\Models\User;

$user = new User();
$user = $user->find(1);

$profile = $user->hasOne('Profile', 'user_id');

if ($profile) {
    echo "User profile bio: " . $profile->bio;
} else {
    echo "No profile found for this user.";
}

Notes

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

  • Internally, this method uses a raw SQL query with a LIMIT 1 clause to ensure only one record is returned.

  • The method returns a fully populated instance of the related model using mapResultToObject().

  • If the $localKey property is not set on the current model instance, the method will return null.

  • Useful for relationships like: User → Profile, Order → Invoice, Product → Stock.

Behavior

  • Instantiates the related model dynamically based on the class name.

  • Uses the local key value from the current model to filter the related table via the foreign key.

  • Returns the related object or null depending on the match result.


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