【发布时间】:2021-05-13 01:11:26
【问题描述】:
我的应用中有以下模型:
User.php
<?php namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Kodeine\Acl\Traits\HasRole;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword, HasRole;
/**
* The database table used by the model.
*
* @var stringSS
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password', 'is_active'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function customer_details()
{
return $this->hasOne('App\Models\CustomerDetails', 'user_id');
}
}
CustomerDetails.php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CustomerDetails extends Model {
protected $table = 'customer_details';
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $appends = ['full_name'];
public function getFullNameAttribute()
{
return $this->attributes['first_name'] .' '. $this->attributes['last_name'];
}
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function invoices() {
return $this->hasMany('App\Models\Invoices', 'customer_id');
}
}
现在我正在尝试运行以下查询:
$user = User::select('email', 'phone')->where('id', Auth::user()->id)->with('customer_details')->first();
现在我要做的是从我的 users 表和 first_nameemail 和 phone 号码/strong>,last_name 来自我的 customer_details 表,但每当我尝试此操作时,它总是将 customer_details 返回为 null。此功能将仅在一个页面上使用,这意味着其他页面可能需要所有详细信息,但不是这个,因此我想创建一个单独的 Eloquent 关系来执行此操作。
【问题讨论】:
-
在您的 User.php 文件中,您错过了指定 localKey 与外键比较:
return $this->hasOne('App\Models\CustomerDetails', 'user_id');它应该是:return $this->hasOne('App\Models\CustomerDetails', 'user_id','id');