问题描述
我正在开发一个有两个守卫(网络和管理员)
的社交网络系统网络防护面向公共用户,管理员防护面向后端用户。还有两个模型用户和管理员模型
系统的功能之一是用户能够创建自己的个人资料。用户模型和个人资料模型之间的关系是一对一的关系,它们是我的迁移
用户迁移
Schema::create('users',function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('active')->default(1);
$table->rememberToken();
$table->softDeletes();
$table->timestamps();
});
配置文件迁移
Schema::create('profiles',function (Blueprint $table) {
$table->id();
$table->string('name');
$table->date('dob')->nullable();
$table->unsignedBigInteger('user_id')->nullable()->unique();
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null')->onUpdate('cascade');
$table->mediumText('address')->nullable();
$table->text('bio')->nullable();
$table->enum('sex',['male','female'])->default('female');
$table->string('mobile')->nullable();
$table->softDeletes();
$table->timestamps();
});
此外,管理员可以使用或不使用用户模型创建配置文件,因此为什么在配置文件表中将 User_id 属性 设置为可以为空。我想存储创建和更新配置文件的 id 取决于警卫(Web 或管理员)。我尝试了多态关系,但还没有成功。
我设法通过添加两个变形属性来更新表配置文件
Schema::table('profiles',function (Blueprint $table) {
$table->nullableMorphs('creatable');
$table->nullableMorphs('updatable');
});
我想存储模型 id 和类型取决于自动使用 trait 的 User Guard。 CreateUpdateBy Trait 文件是
trait CreatedUpdatedBy
{
public static function bootCreatedUpdatedBy()
{
static::creating(function (Model $model) {
if(auth()->check()) {
//query goes here
}
});
/* filter by profile id */
static::updating(function (Model $model) {
if(auth()->check()) {
//query goes here
}
});
}
}
配置文件模型
class Profile extends BaseModel
{
use CreateUpdateBy;
public function creatable()
{
return $this->morphTo();
}
public function updatable()
{
return $this->morphTo();
}
}
管理模型
class Admin extends Authenticatable
{
use Notifiable,HasRoles,SoftDeletes;
/* Define guard to use */
protected $guard = 'admin';
public function created_by()
{
return $this->morphMany(Profile::class,'creatable');
}
public function updated_by()
{
return $this->morphMany(Profile::class,'updatable');
}
}
用户模型
class User extends Authenticatable implements MustVerifyEmail
{
public function profile()
{
return $this->hasOne(Profile::class);
}
public function creatable()
{
return $this->morphOne(Profile::class,'creatable','creatable_type','creatable_id');
}
public function updatable()
{
return $this->morphOne(Profile::class,'updatable','updatable_type','updatable_id');
}
}
我如何使用 trait 来实现这一点,或者是否有其他我准备学习的方法。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)