Laravel一对多关系角色保留

时间:2016-08-08 18:57:05

标签: laravel

我有一个关系,其中Order hasOne(belongsTo)位置,该位置可能有多个(属于许多订单)..

我应该为每个雄辩的模型使用哪种方法.. 哪个模型应该有(Has)方法,哪个应该有(Belongs)方法,取决于什么,我可以用两种方式阅读它。

我需要一个普遍的角色..当我能以两种方式阅读这种关系时... 订单hasOne位置,所以位置belongsToMany订单。 和.. 订单属于位置,所以位置有多个订单。

这里的角色是什么?

这是我有的表..

Location table..

        Schema::create('locations', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('location_id')->unsigned()->index();
            $table->integer('manager_id')->unsigned()->index();
            $table->string('name');
            $table->string('address')->nullable();
            $table->string('city');
            $table->float('latitude')->nullable();
            $table->float('longitude')->nullable();
            $table->timestamps();
        });
````

and Orders Table

````
        Schema::create('orders', function (Blueprint $table) {
            $table->increments('id')->unsigned()->index();
            $table->string('title');
            $table->text('description');
            $table->string('trade');
            $table->string('contact');
            $table->enum('priority',['Regular-72h','Important-48h','Urgent-24h','Crisis-psh']);
            $table->text('notes')->nullable();
            $table->integer('location_id')->unsigned();
            $table->integer('user_id')->unsigned()->index();
            $table->timestamp('entry');
            $table->timestamp('exit');
            $table->integer('close_key')->unsigned();
            $table->softDeletes();
            $table->timestamps();
        });

我在这里搜索,但我问的相同点并没有发现。

2 个答案:

答案 0 :(得分:0)

我从@Snapey

的laracasts中得到了答案

Answer at The Laracasts

错误发生在location_id列中。

答案 1 :(得分:0)

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


class Order {
...
    public function location() {
        return $this->belongsTo('App\Location');
    }
}

这样想:

您的位置可以有多个订单(hasMany),一个订单属于某个位置(belongsTo)。

您可以找到更为一般性的解释here