我只使用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)
执行。
答案 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);