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

问题描述 投票:1回答:1

我只是设置模型AssetbelongsToMany房间和模型RoomhasMany资产关系。我还创建了一个数据透视表,用于存储房间和资产的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()'d code on第1行

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

laravel laravel-5
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.