I just setup model Asset with belongsToMany rooms and model Room with hasMany assets relationships. I also created a pivot table that stores both the ids of room and assets.
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();
});
}
I added an asset via php artisan tinker as:
$asset = new App\Asset;
$asset->name = "Lamp";
$asset->slug = "lamp";
$asset->price = 40;
$asset->save();
Now how do I add an asset to a room so that it also adds an entry to the pivot table?
$room = new App\Room;
$room->number = 1;
$room->status = 1;
$room->asset...?
$room->save();
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire