2015-10-05 7 views
0

Я использую Laravel 5.1 Просто хочу спросить, как отобразить ORM мастер-деталь, когда ребенок не возвращают данные, основные данные, не показываяLaravel Eloquent Master Detail результат

Это мой Мастер Модель

<?php 

namespace SpekWeb; 

use Illuminate\Database\Eloquent\Model; 

    class ProdukGroup extends Model 
    { 
     public $table = 'product_group'; 
     public $primaryKey = 'prd_group'; 

     public function telcoProduct() { 
      return $this->hasMany('SpekWeb\TelcoProduct', 'prd_group', 'prd_group'); 
     } 
    } 

Child Model

<?php 

namespace SpekWeb; 

use Illuminate\Database\Eloquent\Model; 

class TelcoProduct extends Model 
{ 
    public $table = 'telco_product'; 
    public $primaryKey = 'tel_prd'; 
} 

И это мой контроллер

<?php 

namespace SpekWeb\Http\Controllers; 

use Illuminate\Http\Request; 
use SpekWeb\Http\Requests; 
use SpekWeb\Http\Controllers\Controller; 
use SpekWeb\ProdukGroup; 
use SpekWeb\TelcoProduct; 

class ProdukController extends Controller 
{ 
    /** 
    * Display a listing of the resource. 
    * 
    * @return \Illuminate\Http\Response 
    */ 
    public function index() 
    { 
     $memberPrices = ProdukGroup::with(array(
      'telcoProduct' => function($tpJoin) { 
       $tpJoin->join('wd_productprice','telco_product.tel_prd','=','wd_productprice.tel_prd'); 
       $tpJoin->where('charge','>=',0); 
       $tpJoin->whereMemType('1'); //variabel 
       $tpJoin->where(function($qWhere) { 
        $qWhere->whereKodeKec('ASTAY'); //variabel 
        $qWhere->orWhereNull('cluster_gid'); 
       }); 
      }, 
      ) 
     ) 
     ->has('telcoProduct') 
     ->get(); 
     return $memberPrices; 
    } 
} 

Я хочу, чтобы основная запись не показывалась, когда я отфильтровывал код внутри области «с», используя -> has («telcoProduct») все еще не работает для меня. Основная запись по-прежнему отображается в Blade Views. Есть ли уловка для решения этих проблем?

ответ

0

Добавить функцию whereHas перед вашим with. Это по существу похоже на то, что «если у вас есть, дайте мне все записи, соответствующие этим критериям».

Ваш запрос должен выглядеть так (не проверен).

public function index() 
{ 
    $memberPrices = ProdukGroup::whereHas('telco_product', function($query) { 
      $query->join('wd_productprice','telco_product.tel_prd','=','wd_productprice.tel_prd'); 
      $query->where('charge','>=',0); 
      $query->whereMemType('1'); //variabel 
      $query->where(function($qWhere) { 
       $qWhere->whereKodeKec('ASTAY'); //variabel 
       $qWhere->orWhereNull('cluster_gid'); 
      }); 
     }, 
     ) 
    ) 
    ->with(array(
     'telcoProduct' => function($tpJoin) { 
      $tpJoin->join('wd_productprice','telco_product.tel_prd','=','wd_productprice.tel_prd'); 
      $tpJoin->where('charge','>=',0); 
      $tpJoin->whereMemType(1); //this value replace by dynamic Input 
      $tpJoin->where(function($qWhere) { 
       $qWhere->whereKodeKec('ASTAY'); //this value replace by dynamic Input 
       $qWhere->orWhereNull('cluster_gid'); 
      }); 
     }, 
    )) 
    ->get(); 
    return $memberPrices; 
} 
+0

Ваш измененный запрос возвращает только данные ProdukGroup. Я хочу, чтобы $ memberPrice также возвращала свою дочернюю запись. –

+0

Смотрите мое обновленное сообщение. 'whereHas' проверяет только определенные критерии, но не хочет их загружать. – Tim

0

Thanx @ Тим

Но когда я с помощью, как вы сказали с этим кодом:

$memberPrices = ProdukGroup::whereHas('telcoProduct', function($tpHas){ 
      $tpHas->join('wd_productprice','telco_product.tel_prd','=','wd_productprice.tel_prd'); 
      $tpHas->where('charge','>=',0); 
      $tpHas->whereMemType(1); //this value replace by dynamic Input 
      $tpHas->where(function($qWhere) { 
       $qWhere->whereKodeKec('ASTAY'); //this value replace by dynamic Input 
       $qWhere->orWhereNull('cluster_gid'); 
      }); 
     } 
    ) 
    ->with(array(
     'telcoProduct' => function($tpJoin) { 
      $tpJoin->join('wd_productprice','telco_product.tel_prd','=','wd_productprice.tel_prd'); 
     }, 
    )) 
    ->has('telcoProduct') 
    ->get(); 
    return $memberPrices; 

Я получил этот результат:

"prd_group": 1, 
"grp_name": "Telkomsel", 
"topup_code": "777", 
"balance_code": "776", 
"tel_id": 1, 
"product_type": "reguler", 
"with_code": 1, 
"telco_product": [ 
    { 
     "tel_prd": 4, 
     "prd_group": 1, 
     "prd_value": 5000, 
     "stock": null, 
     "keyword": "S5", 
     "charge": 0, 
     "price": 5000, 
     "mem_type": 1, 
     "prd_id": 4, 
     "cluster_gid": null, 
     "kode_kec": null 
    }, 
    { 
     "tel_prd": 4, 
     "prd_group": 1, 
     "prd_value": 5000, 
     "stock": null, 
     "keyword": "S5", 
     "charge": 0, 
     "price": 5100, 
     "mem_type": 2, 
     "prd_id": 4, 
     "cluster_gid": null, 
     "kode_kec": null 
    }, 
] 

Пожалуйста, проверьте 2-й записи telco_product, он не соответствует условию запроса

$ tpHas-> whereMemType (1);

Его показать все записи внутри telcoProduct присоединиться wd_productprice

Я попробовать этот код затем:

$memberPrices = ProdukGroup::whereHas('telcoProduct', function($tpHas){ 
      $tpHas->join('wd_productprice','telco_product.tel_prd','=','wd_productprice.tel_prd'); 
      $tpHas->where('charge','>=',0); 
      $tpHas->whereMemType(1); //this value replace by dynamic Input 
      $tpHas->where(function($qWhere) { 
       $qWhere->whereKodeKec('ASTAY'); //this value replace by dynamic Input 
       $qWhere->orWhereNull('cluster_gid'); 
      }); 
     } 
    ) 
    ->with(array(
     'telcoProduct' => function($tpJoin) { 
      $tpJoin->join('wd_productprice','telco_product.tel_prd','=','wd_productprice.tel_prd'); 
      $tpJoin->where('charge','>=',0); 
      $tpJoin->whereMemType(1); //this value replace by dynamic Input 
      $tpJoin->where(function($qWhere) { 
       $qWhere->whereKodeKec('ASTAY'); //this value replace by dynamic Input 
       $qWhere->orWhereNull('cluster_gid'); 
      }); 
     }, 
    )) 
    ->has('telcoProduct') 
    ->get(); 
    return $memberPrices; 

И я получил результат, как я ожидал

"prd_group": 1, 
"grp_name": "Telkomsel", 
"topup_code": "777", 
"balance_code": "776", 
"tel_id": 1, 
"product_type": "reguler", 
"with_code": 1, 
"telco_product": [ 
    { 
    "tel_prd": 4, 
    "prd_group": 1, 
    "prd_value": 5000, 
    "stock": null, 
    "keyword": "S5", 
    "charge": 0, 
    "price": 5000, 
    "mem_type": 1, 
    "prd_id": 4, 
    "cluster_gid": null, 
    "kode_kec": null 
    }, 
    { 
    "tel_prd": 4, 
    "prd_group": 1, 
    "prd_value": 5000, 
    "stock": null, 
    "keyword": "SS5", 
    "charge": 0, 
    "price": 5000, 
    "mem_type": 1, 
    "prd_id": 148, 
    "cluster_gid": 3, 
    "kode_kec": "ASTAY" 
    } 
] 

Является ли моя техника правильной? Должен ли я дважды писать условие в запросе?

Thx

+0

Да, это, к сожалению, правильно. Критерии не разделены, поэтому вам необходимо отфильтровать все родительские объекты с помощью 'whereHas', а затем загрузить их с помощью' with'. Спасибо, что указал на недостатки моего кода, я обновлю его. – Tim