Illuminate\Database\Eloquent\Model::belongsTo PHP Method

belongsTo() public method

Define an inverse one-to-one or many relationship.
public belongsTo ( string $related, string $foreignKey = null, string $otherKey = null, string $relation = null ) : BelongsTo
$related string
$foreignKey string
$otherKey string
$relation string
return Illuminate\Database\Eloquent\Relations\BelongsTo
    public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
    {
        // If no relation name was given, we will use this debug backtrace to extract
        // the calling method's name and use that as the relationship name as most
        // of the time this will be what we desire to use for the relationships.
        if (is_null($relation)) {
            list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
            $relation = $caller['function'];
        }
        // If no foreign key was supplied, we can use a backtrace to guess the proper
        // foreign key name by using the name of the relationship function, which
        // when combined with an "_id" should conventionally match the columns.
        if (is_null($foreignKey)) {
            $foreignKey = Str::snake($relation) . '_id';
        }
        $instance = new $related();
        if (!$instance->getConnectionName()) {
            $instance->setConnection($this->connection);
        }
        // Once we have the foreign key names, we'll just create a new Eloquent query
        // for the related models and returns the relationship instance which will
        // actually be responsible for retrieving and hydrating every relations.
        $query = $instance->newQuery();
        $otherKey = $otherKey ?: $instance->getKeyName();
        return new BelongsTo($query, $this, $foreignKey, $otherKey, $relation);
    }

Usage Example

Example #1
0
 public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
 {
     return parent::belongsTo($related, $foreignKey, $this->isOracleModel ? strtolower($otherKey) : $otherKey, $relation);
 }
All Usage Examples Of Illuminate\Database\Eloquent\Model::belongsTo
Model