该集合实例上不存在属性[client]

时间:2018-12-29 03:53:53

标签: sql laravel laravel-5 eloquent

我无法获得预订表中的外键的值。

预订表

<?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;

2 个答案:

答案 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;