刚刚在Laravel(5.4)完成了我的“朋友”系统,我正在研究一个项目。我称之为“连接”。一切都很好,我现在正试图清理一切。
从一开始,按照教程和SO答案,我将每个方法都放在我的User
模型中(不是 错误:连接与用户相关)。但我想清理并将与我的连接相关的所有内容放入名为Connection
的模型中。
User
模型是否应该处理与连接相关的所有内容,或者我的清洁愿望是否合理且Connection
模型是否合法?User
现在我不再在课堂上了$this
变得毫无意义?namespace App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Connection extends Authenticatable
{
const PENDING = 0;
const ACCEPTED = 1;
const REJECTED = 2;
}
namespace App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
// Get connections the user initiated by himself
public function connectionsOfOwner() {
return $this->belongsToMany(User::class, 'connections', 'user_id', 'connection_id')->withPivot('status');
}
// Get connections the user has been invited to
public function connectionsOf() {
return $this->belongsToMany(User::class, 'connections', 'connection_id', 'user_id')->withPivot('status');
}
// Accessor allowing to call $this->connections
public function getConnectionsAttribute() {
if (!array_key_exists('connections', $this->relations)) {
$this->loadConnections();
}
return $this->getRelation('connections');
}
// Check if a Laravel relation named "connection" exists
protected function loadConnections() {
if (!array_key_exists('connections', $this->relations)) {
$this->setRelation('connections', $this->mergeConnections());
}
}
// Merge "connectionsOfOwner" and "connectionsOf"
protected function mergeConnections() {
return $this->connectionsOfOwner->merge($this->connectionsOf);
}
// Get pending connections
public function getPendingConnections() {
$filtered = $this->connections->filter(function ($value, $key) {
if ($value->pivot->status == 0) {
return $value;
}
});
return $filtered;
}
// Get accepted connections
public function getAcceptedConnections() {
$filtered = $this->connections->filter(function ($value, $key) {
if ($value->pivot->status == 1) {
return $value;
}
});
return $filtered;
}
// Add a connection
public function addConnection($user) {
$this->connectionsOfOwner()->attach($user->id);
}
// Accept a connection
public function acceptConnection($user) {
$this->connectionsOf()->syncWithoutDetaching([$user->id => ['status' => Connection::ACCEPTED]]);
$this->connectionsOfOwner()->attach($user->id, ['status' => Connection::ACCEPTED]);
}
// Remove a connection
public function removeConnection($user) {
$this->connectionsOfOwner()->detach($user->id);
$this->connectionsOf()->detach($user->id);
}
}
答案 0 :(得分:0)
可能您可以跳过连接模型并将该功能保存在用户模型中使用的特征“HasConnections”中。
Jeffrey Way在Laracon2017中简要介绍了这种方法:https://streamacon.com/video/laracon-us-2017/day-2-jeffrey-way
祝你好运!