嗨,我创建了一个只存储电话号码数字的赋值函数。这是我的配置文件模型中的代码。
public function setPhoneAttribute($phone)
{
$this->attributes['phone'] = preg_replace("/[^0-9]/","",$phone);
}
当我创建一个新记录时,这是有效的,但如果我更新记录,它就不起作用。我的问题是,如何在创建和更新时执行Mutator?
以下是我如何在控制器中更新和创建:
namespace AppHttpControllers;
use AppHttpRequests;
use AppHttpRequestsProfileRequest;
use AppHttpControllersController;
use IlluminateHttpRequest;
use Auth;
use AppProfile;
class ProfileController extends Controller {
public function create(ProfileRequest $request)
{
// Check if the user does not have a profile yet
if(!Auth::user()->profile()->first()){
// Save to database
$saveToDatabase = Auth::user()->profile()->create($request->all());
return $saveToDatabase;
}
}
public function update(Profile $profile, ProfileRequest $request)
{
// Save to database
$saveToDatabase = Auth::user()->profile()->update($request->all());
return $saveToDatabase;
}
}
下面是发生的事情:
Auth::user()->profile()->create($request->all())
对您的关系调用create
方法(HasOneOrMany
)。然后,此方法创建相关模型的新实例。这一点很重要,因为显然只有当通过模型创建记录时才使用属性赋值函数。
但是,关系对象没有任何update
方法。(有一个也没有意义…)。所以,当你做Auth::user()->profile()->update($request->all())
时,会发生什么呢。update
调用get被代理到查询生成器实例(与关系匹配)。这导致了类似这样的事情被执行:
UPDATE profiles SET foo = 'bar' WHERE [relationship conditions]
它根本不使用该模型。因此,突变子不起作用。
相反,您必须在实际的相关模型上调用update
方法。您只需将关系调用为如下属性即可访问它:
$saveToDatabase = Auth::user()->profile->update($request->all());
// ^^
// no parentheses
如果Profile
模型被正确地注入,你实际上也可以使用它:
public function update(Profile $profile, ProfileRequest $request)
{
// Save to database
$saveToDatabase = $profile->update($request->all());
return $saveToDatabase;
}
使用此代码而不是您的代码
$saveToDatabase = Auth::user()->profile->update($request->all());