在 laravel 5.8 中进行方法调用时,它不会向我提供 return 数据

It does not return data to me when making the method call in laravel 5.8

我根据 Laravel 的文档在模型中创建关系时出现问题。

我有我的区号 table 和我的电话 phone table,一个区号可以属于许多 phone,但一个 phone只有一个区号给我留下了一对多的关系

我将向您展示我的模型及其关系。

Phone.php

/**
 * The table associated with the model.
 * 
 * @var string
 * @author Luis Morales
 */
protected $table = 'PHONES';

/**
 * The primary key associated with the table.
 *
 * @var string
 * @author Luis Morales
 */
protected $primaryKey = 'PHONES_ID';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 * @author Luis Morales
 */
protected $fillable = [
    'AREACODES_ID', 'PHONE', 'DATE', 'USERS_ID',
];

/**
 * Indicates if the model should be timestamped.
 *
 * @var bool
 * @author Luis Morales
 */
public $timestamps = false;

/**
 * Get the user for the phone
 * 
 * @author Luis Morales
 */
public function users(){
    return $this->belongsTo('App\User');
}

/**
 * Get the area code for the phone
 * 
 * @author Luis Morales
 */
public function areacodes(){
    return $this->belongsTo('App\AreaCode');
}   

AreaCode.php

/**
 * The table associated with the model.
 * 
 * @var string
 * @author Luis Morales
 */
protected $table = 'AREACODES';

/**
 * The primary key associated with the table.
 *
 * @var string
 * @author Luis Morales
 */
protected $primaryKey = 'AREACODES_ID';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 * @author Luis Morales
 */
protected $fillable = [
    'CODE', 'CITY', 'STATESZONE_ID',
];

/**
 * Indicates if the model should be timestamped.
 *
 * @var bool
 * @author Luis Morales
 */
public $timestamps = false;

/**
 * Get the phone for the area codes
 *
 * @author Luis Morales
 */
public function phones(){
    return $this->hasMany('App\Phone');
}

在我的控制器中调用如下

GenerateNumbersController.php

$phones = Phone::where('DATE',$searchOrCreate)
                ->chunk(500,function($phone){
                        foreach ($phone as $p) {
                        dd($p->areacodes);
                    }
        });

searchOrCreate 变量有一个日期格式的值,我对 $phone 进行了 dd,它显示的所有关系都以 null

形式出现

您调用了错误的方法。 dd($p->区号);因为在您的 phone 模型中,您的模型名称是区号,与您调用的函数不匹配。解决方案将 dd($p->areacode); 更改为 dd($p->areacodes);

将您的 return 语句更改为 return $this->belongsTo( 'App\AreaCode', 'AREACODES_ID', 'PHONES_ID');