Ash*_*Ash 3 php laravel eloquent
我的一个模型中有一个自定义函数。它看起来像这样:
    public function newWithTeam($data, $team_id = false){
    $levels = Permissions::get_levels();
    $this->email    = $data['email'];
    $this->password = bcrypt($data['password']);
    $this->username = $data['username'];
    $this->save();
    $profile =  new Profile(['name' => $data['name'],'bio'  => $data['bio']]);
    $this->profile()->save($profile);
    }
在这里,您可以看到我存储了email,password和username为对象属性,然后再点击save()
相反,我想在一行中执行此操作,例如:
$this->store(['email' => $data['email], 'password' => $data['password], 'username' => $data['username']]);
$this->save();
我知道该create()方法存在,但是当我使用它时,以下行 
$this->profile()->save($profile);无法正常工作。我认为该create()功能由于save()某种原因无法正常工作!是否有与上述store()功能等效的功能?
您可以使用该fill()方法来实现您想要的。
但是在使用它之前,您应该了解一些事情。
由于安全原因,Laravel 模型可以防止大量分配,要使用该fill()方法,您需要定义可以使用fillable或guarded属性填充模型的哪些属性。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserModel extends Model
{
    protected $fillable = ['email', 'password', 'username'];
    public function newWithTeam($data, $team_id = false){
        $levels = Permissions::get_levels();
        $this->fill([
            'email'    => $data['email'],
            'password' => bcrypt($data['password']),
            'username' => $data['username']
        ]);
        $this->save();
        $profile = new Profile([
            'name' => $data['name'],
            'bio' => $data['bio']
        ]);
        $this->profile()->save($profile);
    }
}
该fillable属性的功能类似于批量分配的白名单。如果您想要另一种方式,您可以使用guarded功能类似于黑名单的属性。这意味着guarded属性中列出的每一列都不能用于批量分配,其他所有列都可以,这是您的选择。
关于您的最后一条语句,如果您查看该create()方法的实现,您会发现它接受一个常规的 php 数组,而该save()方法将接受一个 Eloquent Model 实例。这就是为什么create()无法接收您的$profile变量的原因。
我希望这有帮助。