Laravel关系和外键约束

时间:2018-10-23 06:43:40

标签: laravel foreign-keys migration relationship

我有两个模型和迁移表。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    public function guest()
    {
        return $this->hasOne(Guest::class);
    }
}

-     

namespace App;

use Illuminate\Database\Eloquent\Model;

class Guest extends Model
{
    public function room()
    {
        return $this->hasMany(Room::class);
    }
}

房间-> id,平方米,guest_id

客人-> ID,姓名,姓氏,电子邮件,电话,room_id(必填)

在模型中实现的房间hasOne Guest->

客人有很多房间->已在模型中实现

如果创建客人,则必须添加房间号。带有相应ID的room_table中的房间应使用guest_id自动更新。

示例 新访客:id(2),姓名,姓氏,电话,电子邮件,room_id(3)-> ID为3的房间应显示给ID为2的访客。

我该如何实现?

3 个答案:

答案 0 :(得分:1)

在您的控制器中添加以下功能:

public function CheckInUser($guest_id,$room_id)

 $guest = Guest::where('id',$guest_id)->firstOrFail();
 $room = Room::where('id',$room_id)->firstOrFail();

 $guest['room_id'] = $room_id;
 $guest->save();

 $room['guest_id'] = $guest_id;
 $room->save();

}

现在,您可以通过调用以下函数来随时更改宾客房间,如下所示:

CheckInUser(2,3);

答案 1 :(得分:0)

客房等级

class Room extends \Illuminate\Database\Eloquent\Model {
    /**
     * @var string
     */
    protected $table = 'room';

    /**
     * Relationship - Belongs To - Guest
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function guest()
    {
        return $this->belongsTo(Guest::class,'guest_id');
    }
}

来宾班

class Guest extends \Illuminate\Database\Eloquent\Model {
    /**
     * @var string
     */
    protected $table='guest';

    /**
     * Relationship - Has Many - Rooms
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function rooms()
    {
        return $this->hasMany(Room::class,'guest_id');
    }
}

用于保存上面定义的关系的代码:

$room = Room::create();
$room->save();

$guest = Guest::create();
$guest->save();
//Add guest to room - 1st method
$guest->rooms()->save($room);

//Add guest to room - 2nd method
$room->guest()->associate($guest);

答案 2 :(得分:0)

模特嘉宾

namespace App;

use Illuminate\Database\Eloquent\Model;

class Guest extends Model
{
    public function room()
    {
        return $this->hasMany(Room::class);
    }
}

和房间模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    public function guest()
    {
        return $this->hasOne(Guest::class);
    }
}

您控制器中的所有模型都已在构造器中加载

 $gust_id=$request->get('guest_id');
 $room_id=$request->get('count_of_rooms');
 $squrmtr=$request->get('squaremeters');

在保存访客数据后让您拥有多个房间,您必须将其保存

for($i = 0; $i < count($request->get('count_of_rooms')); $i++)
{
    $rooms[] = new Room([
        'guset_id'  => $guest->id,
        'squaremeters' => $squrmtr[$i],
    ]);
}
$guest->room()->saveMany($rooms);