这是我的问题:
$batchDetails=BatchModel::join('class', 'batch.Class', '=', 'class.AutoID')
->get()
->toArray();
BatchModel:
<?php
class BatchModel extends Eloquent
{
protected $primaryKey = 'AutoID';
protected $table = 'batch';
protected $fillable = array('Class','batch','Statedate','Enddate');
public $timestamps = false;
public function batch(){
return $this->hasMany('BatchModel', 'Class');
}
public static $rules = array(
'Class' => 'required',
'batch' => 'required',
'Statedate' => 'required',
'Enddate' => 'required',
);
}
ClassModel:
<?php
class ClassModel extends Eloquent
{
protected $primaryKey = 'AutoID';
protected $created_at = 'CreatedAt';
protected $updated_at = 'UpdatedAt';
protected $table = 'class';
protected $guarded = array('ClassName');
protected $fillable = array('ClassName', 'ClassSection', 'ClassCode');
public function classModel(){
return $this->belongsTo('ClassModel', 'Class');
}
public $timestamps = true;
public static $rules = array(
'ClassName' => array('required', 'unique:class','regex:/^./'),
'ClassSection' => 'required',
'ClassCode' => array('required', 'unique:class')
);
}
我不想使用像“class and batch”这样的表名。我只想使用模型名称而不是表和表属性。
所以我的问题是如何才能使用模型名称进行上述连接查询?
答案 0 :(得分:2)
您可以使用Eloquent relations。
class BatchModel extends Eloquent {
public function classModel(){ // normally I'd use only "class" but that's a reserved word so..
return $this->belongsTo('ClassModel', 'Class');
}
}
class ClassModel extends Eloquent {
protected $primaryKey = 'AutoID';
public function batch(){
return $this->hasMany('BatchModel', 'Class');
}
}
不确定我是否把一切都搞定了,但它应该是这样的。现在您可以像这样查询:
$batchDetails = BatchModel::with('classModel')->get();