Laravel雄辩为hasMany添加了额外的模型

时间:2015-06-25 09:21:00

标签: laravel eloquent laravel-5

我有一个user模型,每个用户都有多个licenses。有2个默认许可证适用于不在licenses表中的所有用户,并且需要使用User模型中包含的某些数据动态创建。

每次获取用户许可并将其添加到licenses()的输出时,如何创建2个许可?

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    protected $table = 'users';
    public $timestamps = false;

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    public function licenses()
    {
        return $this->hasMany('App\License', 'user_id', 'id')->where('deleted', '=', '0');
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在模型中创建一个额外的功能,您可以在其中调用许可证并添加额外的许可证。

请记住测试使用此功能的所有地方,这样就不会发生任何奇怪的事情。

<?php

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    protected $table = 'users';
    public $timestamps = false;

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    // HasMany function
    public function _licenses()
    {
        return $this->hasMany('App\License', 'user_id', 'id')->where('deleted', '=', '0');
    }

    // New licenses function
    public function licenses() 
    {
        // Get licenses from database
        $licenses = $this->_licenses;

        // Add  other lisences
        $licenses = $licenses->add(new License([ "user_id" => $this->id, "name" => "foo" ]));
        $licenses = $licenses->add(new License([ "user_id" => $this->id, "name" => "bar" ]));

        // Return the new collection
        return $licenses
    }
}