如何使用数据透视表添加新记录ith belongsToMany和hasMany关系?

时间:2017-12-25 11:20:16

标签: laravel laravel-5

我只使用Asset个房间设置模型belongsToMany,并使用Room资产关系建立hasMany模型。我还创建了一个数据透视表,用于存储房间和资产的ID。

MODELS

class Asset extends Model
{

    protected $fillable = [ 'name', 'slug', 'price' ];

    public function room()
    {
        return $this->belongsToMany('App\Room');
    }
}

class Room extends Model {

    protected $fillable = [ 'number', 'status' ];

    public function assets()        
    { 
        $this->hasMany('App\Asset'); }
    }
}

MIGRATIONS

public function up()
    {
        Schema::create('assets', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('slug');
            $table->string('price');

            $table->timestamps();
            $table->softDeletes();
        });
    }

 public function up()
    {
        Schema::create('asset_room', function(Blueprint $table) {
            $table->integer('asset_id')->unsigned();
            $table->foreign('asset_id')->references('id')->on('assets');
            $table->integer('room_id')->unsigned();
            $table->foreign('room_id')->references('id')->on('rooms');
            $table->unique(['asset_id', 'room_id']);
            $table->timestamps();
        });
    }

我通过php artisan tinker添加了一项资产:

$asset = new App\Asset;
$asset->name = "Lamp";
$asset->slug = "lamp";
$asset->price = 40;
$asset->save();

现在如何将资产添加到房间,以便它还在数据透视表中添加一个条目?

$room = new App\Room;
$room->number = 1;
$room->status = 1;
$room->asset...?
$room->save();

UPDATE

根据Alexey的建议,我在Room模式中更新了以下函数,因为它是belongsToMany而不是hasMany关系。

public function assets()        
{ 
    $this->belongsToMany('App\Asset');
}

我创建了一个ID为1的资产。当尝试将资产附加到房间时:

$room->assets()->attach(1);

我收到以下错误:

  

PHP致命错误:在C:\ xampp \ htdocs \ hotel \ vendor \ psy \ psysh \ src \ Psy \ ExecutionLoop \ Loop.php(90)中调用null上的成员函数attach():eval()第1行的代码

也打破了Tinker mode (Psy Shell)执行。

1 个答案:

答案 0 :(得分:0)

首先,由于它是多对多关系,因此它应该是belongsToMany()

public function assets()        
{ 
    return $this->belongsToMany('App\Asset');
}

要将资产附加到房间,请使用attach()方法:

$asset = new App\Asset;
$asset->name = "Lamp";
$asset->slug = "lamp";
$asset->price = 40;
$asset->save();

$room = new App\Room;
$room->number = 1;
$room->status = 1;
$room->save();

$room->assets()->attach($asset->id);