2017-08-25 12 views
1

私はLaravel 5.4を実行しています。何らかの理由で1対多の多型関係で列選択を実行できません。私は、関連するテーブルに返される列を制限したい。ここでlaravel eloquent - クエリ 'select'を使用して多型関係をロードできない

は私の1対多の関係の私の「1つの」側です:

class MapNodes extends Model { 

    protected $table = 'map_nodes'; 
    protected $fillable = ['title']; 
    protected $validations = ['title' => 'max:200|string' ]; 
    public function SystemConstants() { 
     return $this->morphMany('App\Modules\Models\SystemConstants', 'imageable'); 
    } 
} 

ここでは私の「多くの側面」テーブルの関係にあります:

class SystemConstants extend Model { 

    protected $table = 'system_constants'; 
    protected $fillable = ['name','imageable_id','imageable_type']; 
    protected $validations = ['name' => 'max:200|string', 
           'imageable_id' => 'integer|required', 
           'imageable_type' => 'max:45|string']; 

    // define this model as polymorphic 
    public function imageable() { 
     return $this->morphTo(); 
    }   
} 

ここで私は2つの方法がありますそれを呼び出すことを試みる。一つはSystemConstants上のすべての列を取得し、第二は、私はちょうど2つの列をしたい:

$temp = MapNodes::with('SystemConstants')->find(25786); 
    $temp = MapNodes::with([ 'SystemConstants' => 
    function($query) { 
     return $query->select('system_constants.id', 'system_constants.name'); 
    } ])->find(25786); 

なぜ最初の呼び出しは、第二の関連レコードを返しますが、しないのですか?以下の両方の呼び出しのSQL文は全く同じように見えます(ただし、2番目の呼び出しでは2つの列のみが必要です)。

select * from `system_constants` where 
    `system_constants`.`imageable_id` in (?) and 
    `system_constants`.`imageable_type` = ? - a:2:{i:0;i:25786;i:1;s:5:"Nodes";} 

select `system_constants`.`id`, `system_constants`.`name` from `system_constants` where 
    `system_constants`.`imageable_id` in (?) and 
    `system_constants`.`imageable_type` = ? - a:2:{i:0;i:25786;i:1;s:5:"Nodes";} 

答えて

0

あなたはselect文で外部キーと主キーの両方を追加する必要があります動作するために:

$temp = MapNodes::with([ 'SystemConstants' => 
    function($query) { 
     return $query->select('system_constants.id', 'system_constants.name', 'system_constants.imageable_id'); 
    } ])->find(25786); 
+0

感謝を!なぜ私は2つのステートメントの間に生成されたSQLが同じであるので、これは動作しませんが、それは動作します! – cardinalPilot