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

belongsToMany() public method

Define a many-to-many relationship.
public belongsToMany ( string $related, string $table = null, string $foreignKey = null, string $otherKey = null, string $relation = null ) : Illuminate\Database\Eloquent\Relations\BelongsToMany
$related string
$table string
$foreignKey string
$otherKey string
$relation string
return Illuminate\Database\Eloquent\Relations\BelongsToMany
    public function belongsToMany($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null)
    {
        // If no relationship name was passed, we will pull backtraces to get the
        // name of the calling function. We will use that function name as the
        // title of this relation since that is a great convention to apply.
        if (is_null($relation)) {
            $relation = $this->getBelongsToManyCaller();
        }
        // First, we'll need to determine the foreign key and "other key" for the
        // relationship. Once we have determined the keys we'll make the query
        // instances as well as the relationship instances we need for this.
        $foreignKey = $foreignKey ?: $this->getForeignKey();
        $instance = new $related();
        if (!$instance->getConnectionName()) {
            $instance->setConnection($this->connection);
        }
        $otherKey = $otherKey ?: $instance->getForeignKey();
        // If no table name was provided, we can guess it by concatenating the two
        // models using underscores in alphabetical order. The two model names
        // are transformed to snake case from their default CamelCase also.
        if (is_null($table)) {
            $table = $this->joiningTable($related);
        }
        // Now we're ready to create a new query builder for the related model and
        // the relationship instances for the relation. The relations will set
        // appropriate query constraint and entirely manages the hydrations.
        $query = $instance->newQuery();
        return new BelongsToMany($query, $this, $table, $foreignKey, $otherKey, $relation);
    }

Usage Example

Example #1
0
 /**
  * For when you still want to use the 'normal' belongsToMany relationship in a CmsModel
  * that should be related to non-CmsModels in the laravel convention
  *
  * @param  string $related
  * @param  string $table
  * @param  string $foreignKey
  * @param  string $otherKey
  * @param  string $relation
  * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  */
 public function belongsToManyNormal($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null)
 {
     return parent::belongsToMany($related, $table, $foreignKey, $otherKey, $relation);
 }
All Usage Examples Of Illuminate\Database\Eloquent\Model::belongsToMany
Model