【发布时间】:2015-05-12 21:09:23
【问题描述】:
我的 Laravel 模型有问题,我正在尝试使用数据库中已有的数据透视表,这是我正在使用的表的布局
客户
工作
客户-工作
我相信错误在我的模型中,我并不完全理解雄辩的语法,但我一直在尝试其他几种方法。我想将主数据库保留在 clients-jobs 表中,以便更轻松地对其进行索引。
这是我的模型: 客户
protected $table = 'clients';
public $timestamps = true;
protected $primaryKey = "id";
public function clientsjobs() {
return $this->belongsTo('ClientsJobs');
}
工作
protected $table = 'jobs';
protected $fillable = array('first_name', 'last_name', 'email');
protected $primaryKey = "id";
public function clientsjobs() {
return $this->belongsToMany('ClientsJobs');
}
ClientsJobs(也许我应该删除这个模型?我用对了吗?)
protected $table = 'clients-jobs';
protected $primaryKey = "id";
public function clients() {
return $this->hasOne('Client', 'id');
}
public function jobs() {
return $this->hasOne('Job', 'id');
}
我用来尝试显示 clients-jobs 表的所有记录的代码在我的一个控制器中是这样的(感谢 sebastien):
$masterArray = array();
ClientsJobs::with('clients', 'jobs')->chunk(200, function($records) use (&$masterArray) { //Chunk Retrieves 200 Records at a time
foreach ($records as $record) {
$masterArray[] = array(
'id' => $record->id, // id
'client_name' => !empty($record->clients) ? $record->clients->fname : "Unknown",
'job_name' => !empty($record->jobs) ? $record->jobs->name : "Unknown",
'wage' => $record->wage,
'productivity'=> $record->productivity,
);
}
});
return $masterArray;
此代码适用于前两条记录,但之后“未知”,我很确定这是因为应用程序认为它是 1:1 关系(我只有 2 个用户和 2 个作业作为虚拟数据)。
在此先感谢您提出的任何建议,如果您看到我所做的令人讨厌的事情,请告诉我
【问题讨论】:
-
嘿!我认出了一个问题... :-)
-
是的,我有点不耐烦了,我需要离开 stackoverflow
标签: php html mysql laravel laravel-4