我有2个相关的模型。它们使用MorphOne关系链接。 第一个模型是用户:
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
/**
* Get all of the owning description models.
*/
public function description()
{
return $this->morphTo();
}
}
第二个与用户类型相关联,在我们的示例中为Trainer:
class Trainer extends Model
{
/**
* Get user, which trainer belongs to.
*/
public function user()
{
return $this->morphOne('App\Models\Users\User', 'description');
}
/**
* Event listeners
*/
public static function boot()
{
parent::boot();
static::created(function($item)
{
event(new TrainerCreated($item));
});
}
}
如您所见,我尝试将事件用于不同的用户类型。在这些事件中,我想访问相关的用户模型,如下所示:$trainer->user
但我找不到正确的顺序来保存这些模型。
我现在拥有的:
class AuthController extends Controller
{
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
$user = Users\User::create([
'name' => $data['name'],
'surname' => $data['surname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
switch ($data['type'])
{
case "trainer":
$supertype = Users\Trainer::create();
break;
default:
$supertype = Users\Visitor::create();
break;
}
if ($supertype)
{
$supertype->user()->save($user);
}
return $user;
}
}
哪个错误,我Trying to get property of non-object
我也尝试了另一种方式,这似乎更符合逻辑:
switch ($data['type'])
{
case "trainer":
$supertype = new Users\Trainer;
break;
default:
$supertype = new Users\Visitor;
break;
}
if ($supertype)
{
$user->description()->associate($supertype);
$supertype->save();
}
会引发另一个错误Class '' not found
。
我尝试了多种其他方式,例如手动设置ID,但它们都会抛出不同的错误而不能正确关联模型。也许手动设置description_id
和description_type
会有所帮助,但此时我没有设置ID。
答案 0 :(得分:1)
我找到了工作解决方案:
class AuthController extends Controller
{
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
$user = Users\User::create([
'name' => $data['name'],
'surname' => $data['surname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
switch ($data['type'])
{
case "trainer":
$supertype = new Users\Trainer;
break;
default:
$supertype = new Users\Visitor;
break;
}
if ($supertype)
{
$supertype->user()->save($user);
$supertype->save();
$user->description()->associate($supertype);
$user->save();
}
return $user;
}
}
User
模型并保存。 $user = Users\User::create([])
Trainer
模型实例。
$supertype = new Users\Trainer;
User
模型添加到MorphOne关系中
在此保存Trainer
模型之后。这将允许我们使用
$trainer->user
活动中的TrainerCreated
。
$supertype->user()->save($user);
$supertype->save();
$user->description()->associate($supertype);
$user->save();