我无法获得预订表中的外键的值。
预订表
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class booking extends Model
{
protected $primaryKey = 'bookingID';
protected $fillable = ['clientID', 'checkInDate', 'checkOutDate', 'roomsCount', 'roomTypeID', 'adultsCount', 'childrenCount', 'amenityID', 'paymentID'];
public function client()
{
return $this->hasOne(Client::class,'clientID');
}
}
客户表
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class client extends Model
{
protected $primaryKey = 'clientID';
protected $fillable = ['fullNmae', 'firstName', 'lastName', 'phoneNumber', 'emailAddress'];
public function booking()
{
return $this->hasMany(Booking::class);
}
}
我尝试按照上一个问题中的建议添加protected $primaryKey = 'bookingID';
和protected $primaryKey = 'clientID';
,但是现在我仍然不能仅从客户表中获取名字。
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
答案 0 :(得分:0)
我需要尝试以下一项:
在您的预订模型中: //'App \ Client'这是您需要放置客户端模型路径的示例
public function client()
{
return $this->belongsTo('App\Client','clientID');
}
在您的客户模型中:
public function booking()
{
return $this->hasMany('App\Booking' , 'clientID');
}
答案 1 :(得分:0)
您正在尝试从以下几行中的集合中获取属性:
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
但是此属性client
是为对象而不是集合定义的。因此,要解决该问题,必须从集合中获取一个对象,如下所示:
$bookingDetail = booking::with('client')->first();
return $bookingDetail->client->firstName;