使用 Eloquent ORM laravel 加入多个 table 模型

Join more then one table model using Eloquent ORM laravel

这是我的查询:

$batchDetails=BatchModel::join('class', 'batch.Class', '=', 'class.AutoID')
    ->get()
    ->toArray();

批量模型:

<?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', 
        );

}

类模型:

<?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" 这样使用 table 这个名字。我只想使用模型名称而不是 table 和 table 属性。

所以我的问题是如何仅使用模型名称进行上述连接查询?

您可以为此使用 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();