推荐文章深入理解 Laravel Eloquent(三)——模型间关系(关联)
其实关联模型的效率是最低的,但是我们可以通过关联模型查看更多的 sql
语句的写法。当然有事业务需求,还是避免不掉需要关联的。
今天就拿用户和角色之间的关系来,分享一下belongsToMany的写法。大家都知道,用户和角色都是多对多的关系,一个用户可以有多个角色,同时一个角色也可被多个用户拥有。下面进入正题...
用户表如下:
角色表如下:
用户和角色的中间表如下:
belongsToMany()有五个参数,每个参数的含义,下面咱们一步步说明
belongsToMany()
多对多这个关联可能不好理解,但是我们可以打开源码,一步步打印
/**
* Define a many-to-many relationship.
*
* @param string $related
* @param string $table
* @param string $foreignPivotKey
* @param string $relatedPivotKey
* @param string $parentKey
* @param string $relatedKey
* @param string $relation
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
$parentKey = null, $relatedKey = 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->guessBelongsToManyRelation();
}
// 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.
$instance = $this->newRelatedInstance($related);
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
$relatedPivotKey = $relatedPivotKey ?: $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);
}
return $this->newBelongsToMany(
$instance->newQuery(), $this, $table, $foreignPivotKey,
$relatedPivotKey, $parentKey ?: $this->getKeyName(),
$relatedKey ?: $instance->getKeyName(), $relation
);
}
$parentKey
第五个参数,如果第三个参数用的不是自己的主键,则需要第五个参数。现在我们使用的是role_id
,第五个参数应该就是role_id
,虽然从sql
语句上看不出来什么,但是你看传递的参数值就知道了,传递的其实就是第五个参数的值
结合上面贴出的数据表,最终的写法如下:
参数一:角色表的模型 参数二:中间表的名称 参数三:中间表中的用户ID外键 参数四:中间表中的角色ID外键
打印出来的SQL如下:
select `la_admin_role`.*, `la_admin_user_role`.`user_id` as `pivot_user_id`, `la_admin_user_role`.`role_id` as `pivot_role_id` from `la_admin_role` inner join `la_admin_user_role` on `la_admin_role`.`id` = `la_admin_user_role`.`role_id` where `la_admin_user_role`.`user_id` in (1, 2);
如有不足之处或者有更好的方法,还希望同志们积极分享。