Laravel 5.1如何使用数据透视表将订单附加到用户?

时间:2015-08-29 10:18:19

标签: laravel laravel-5.1

所以我正在尝试构建一个结构,其中一个用户可以拥有多个订单,一个订单有两个用户(例如:客户和服务该订单的员工)。

这是我的迁移:

用户订单:

Schema::create('order_user', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->integer('user_id')->unsigned()->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->integer('order_id')->unsigned()->index();
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
        $table->timestamps();
    });

订单:

Schema::create('orders', function (Blueprint $table) {
        $table->increments('id');

        $table->string('boostFrom')->nullable();
        $table->string('boostTo')->nullable();
        $table->string('numGames')->nullable();
        $table->decimal('totalPrice');
        $table->string('ipnStatus');

        $table->timestamps();
    });

用户:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });

我还没有设置关系,因为我已经在我的用户和订单模型中测试了它们。但是当我尝试使用以下命令将订单附加到用户时

$user->order()->attach(4);

我收到一个与Builder.php有关的错误,说attach()不存在,但是我按照laravel 5.1文档尝试附加订单。

请您告诉我如何构建所有内容,以便在创建订单时我可以将其附加到用户。

由于

如要求:

class Order extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'orders';

    public function users()
    {
        return $this->hasMany('App\Models\User');
    }
}


class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract
{
    use Authenticatable, CanResetPassword, HasRoleAndPermission;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    protected $guarded = ['id'];

    public function orders()
    {
        return $this->hasMany('App\Models\Order');
    }

}

修补匠错误:

>>> $user->orders()->attach(4)

BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::attach()'

1 个答案:

答案 0 :(得分:2)

您应该使用belongsToMany而不是hasMany,因为您有 many-to-many 关系。 hasMany用于定义 one-to-many 关系。所以你应该这样:

// Order.php
public function users()
{
    return $this->belongsToMany('App\Models\User');
}

和这个

// User.php
public function orders()
{
    return $this->belongsToMany('App\Models\Order');
}