在laravel 5.8中进行方法调用时,它不会向我返回数据

时间:2019-09-06 18:13:36

标签: php laravel eloquent laravel-5.8

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

我有我的区号表和电话表,一个区号可以属于许多电话,但是一部电话只有一个区号,使我与一对多关系

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

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变量具有日期格式的值,我将dd转换为$ phone,它显示的所有关系都为空

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

将您的退货声明更改为  返回$ this-> belongsTo('App \ AreaCode','AREACODES_ID','PHONES_ID');