Laravel:从多个表中选择(优先使用ORM)

时间:2017-11-22 05:54:15

标签: php sql laravel

我正在使用带有postgresql的laravel 5.5

我想运行此查询(实际上在postgresql中运行):

select table1.*
from table1, table2
where
    table1."table2_id" = table2.id
and
    table2."table3_id" = '$id'

我已经拥有:

class table1 extends Model
{
    public function table2()
    {
        return $this->belongsTo('app\table2', 'table2_id');
    }
}

class table2 extends Model
{
    public function table1()
    {
        return $this->hasMany('app\table1', 'table1_id');
    }
    public function table3()
    {
        return $this->belongsTo('app\table3', 'table3_id');
    }
}

class table3 extends Model
{
    public function table2()
    {
        return $this->hasMany('app\table2', 'table2_id');
    }
    public function table1()
    {
        $table1="table1"
        $table2="table2"
        $table3="table3"
        $table2_id="table2_id"
        return DB::table(DB::raw($table1.', '.$table2))->
            select($table1.'.*')->
            where($table1.'.table2_id', "=", $propiedad_table.'.'.$table2_id)->
            where($table2.'.table3_id', "=", "'".$this->id."'")->get();
    }
}

此时我有2个问题,table3-> table1()抛出一个错误,但在错误的描述中有我实际想要的相同查询,当我在postgresql中运行它时它的工作原理,所以idk原因错误,第二个问题是,如果有更好的方法使用Laravel的ORM进行此查询?

编辑:

我遇到的错误是:

"SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for uuid: "table2.id" (SQL: select "table1".* from table1, table2 where "table1"."table2_id" = table2.id and "table2"."table3_id" = '20e0cea9-eb58-4252-aa18-9e28a485d29e')

1 个答案:

答案 0 :(得分:1)

$rs = table1::with('table2.table3')
      ->whereHas('table2',function($q) use ($id){

        $q->whereHas('table3',function ($q) use ($id){
             $q->where('id',$id);
        });

      });

我对你的疑问有点不清楚希望这会有所帮助!