laravel one to Many与多个表的关系,查询未优化?

时间:2014-08-16 12:33:50

标签: laravel eloquent relationship

我有一个表调用table1(我在这里使用了一些假装的表名),如下面的

id_table1    description

模特就像 `

class Table1 extends \Eloquent {
  public $timestamps = false;
  protected $table = 'table1';
  protected $fillable = [ 'description'];

  protected $primaryKey = 'id_table1';

  public function relation5s(){
    return $this->hasMany('Relation5','id_table1','id_table1');
  }
  public function relation4s(){
    return $this->hasMany('Relation4','id_table1','id_table1');
  }
  public function relation3s(){
    return $this->hasMany('Relation3','id_table1','id_table1');
  }
  public function relation2s(){
    return $this->hasMany('Relation2','id_table1','id_table1');
  }
  public function relation1s(){
    return $this->hasMany('Relation1','id_table1','id_table1');
  }

}

此表与5个表名称relation_table1,relation_table2 ......等相关。

以下是关系表的示例模型代码

 <?php

 use Illuminate\Database\Eloquent\Relations;
class Relation1 extends \Eloquent {
  public $timestamps = false;
  protected $table = 'relation_table1';
  protected $fillable = [ 'id_table1','idReseller', 'login', 'password', 'type','etc'];


  public function childs(){

        return $this->hasMany('Relation2','id_relation','id');

  }
  public function table1(){

        return $this->belongsTo('Table1','id_table1','id_table1');
  }
  public function scopeActive($query){
    return $query->whereRaw('type % 2 = 1');
  }
  public function scopeInactive($query){
    return $query->whereRaw('type % 2 = 0');
  }   
}

` 问题是我在下面查询

$level=1; // i am controlling 5 relation tables in same controller via $level from route
$class = "Relation".$level;
     $collection  = new $class;    
$results = $collection->with('Table1')->orderBy($sort,$order)->paginate();

它的工作显示了关系表的所有结果..但它没有解决n + 1查询问题。我的意思是来自relation1的每一行每次在table1上查询..任何想法我怎么能解决这个问题? 提前谢谢

2 个答案:

答案 0 :(得分:0)

看看Eager loading,您正在使用 with 方法,因此它会在第一个查询中加载它们

$level=5
$class = "Relation".$level::with('Table1')->orderBy($sort,$order)->paginate();

答案 1 :(得分:0)

您的代码是正确的,只需将“Table1”替换为“table1”:

$results = $collection->with('table1')->orderBy($sort,$order)->paginate();