我正在开发游戏,目前正在执行管理部分以添加游戏和关卡.
我通过带有“订单”列的数据透视表引用了游戏和关卡.
我的游戏模型:
class Game extends Eloquent {
public function levels() {
return $this->belongsToMany('Level')->withPivot('order');
}
}
我的关卡模型:
class Level extends Eloquent {
public function game() {
return $this->belongsToMany('Game')->withPivot('order');
}
}
我想要实现的是在添加级别时自动填充订单列,并创建moveup()和movedown()函数.
我尝试在关卡模型上设置模型事件来实现此目的,但未成功.
解决方法:
首先,这种顺序是单向的.您不能将同一列用于游戏的关卡顺序,反之亦然.
现在,您可以实现所需的功能,例如通过在关系上重写attach方法来检查当前的最大位置,然后添加下一个以进行相应的插入(而不是创建事件或任何事件,因为这与关卡创建本身无关,而与附加级别无关)游戏).
话虽如此,您将需要扩展Eloquent Model或使用特征以使用您的自定义BelongsToMany关系.像下面这样的事情应该做的工作(没有评论等使其简洁).
// Game model
class Game extends Eloquent {
use SortablePivotModelTrait;
public function levels()
{
return $this->sortableBelongsToMany('Level', 'order')->withPivot('order');
}
//...
}
// SortablePivotModelTrait.php
use Illuminate\Database\Eloquent\Model;
trait SortablePivotModelTrait {
public function sortableBelongsToMany($related, $orderColumn = null, $table = null, $foreignKey = null, $otherKey = null, $relation = null)
{
// all the code of belongsToMany method needs to go here
// ...
// then just:
return new SortableBelongsToMany($query, $this, $table, $foreignKey, $otherKey, $relation, $orderColumn);
}
}
// SortableBelongsToMany.php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class SortableBelongsToMany extends BelongsToMany {
protected $orderColumn;
public function __construct(Builder $query, Model $parent, $table, $foreignKey, $otherKey, $relationName = null, $orderColumn = 'order')
{
$this->orderColumn = $orderColumn;
parent::__construct($query, $parent, $table, $foreignKey, $otherKey, $relationName);
}
public function attach($id, array $attributes = array(), $touch = true)
{
$attributes = array_merge($attributes, [$this->getOrderColumnName() => $this->getNextPosition()]);
return parent::attach($id, $attributes, $touch);
}
public function getNextPosition()
{
return 1 + $this->newPivotQuery()->max($this->getOrderColumnName());
}
public function getOrderColumnName()
{
return $this->orderColumn;
}
}
这样,您可以执行以下操作:
$level = new Level;
// do some stuff with the created level
$game = Game::find($id);
// then
$game->save($level);
// or
$level->save();
$game->levels()->attach($level);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。