Laravel 4: Select row if a relation exists by querying relation

前端 未结 1 1504
礼貌的吻别
礼貌的吻别 2021-01-26 01:24

I am trying to query a products table, and want it to return a collection if a relation exists.

Iteration 1 below queries all rows in t

相关标签:
1条回答
  • 2021-01-26 02:06

    Unfortunately you cannot do this with one swipe in Eloquent yet.

    BUT, there is a way by using the inverse relation, like this:

    public function getFilter($metal = null)
    {
        // filter the metals first
        $metals = Metal::with('products')->where('name', '=' , $metal)->get();
        $products = array();
        foreach($metals as $metal)
        {
               // collect the products from the filtered metals
               $products = array_merge($products, $metal->products->toArray() );
        }
        return $products;
    }
    

    If this is not elegant solution for you, you will either have to use Fluent to construct the query and join the products x metals table manually or pre-join them by overriding the newQuery() method.

    1) alternative approach one.

    public function getFilter($metal = null) {
        return DB::table('products')->join('metal', 'products.id', '=' , 'metal.product_id')
                             ->where('metal.name', $name)
                             ->select(array('products.*'));
    }
    

    2) alternative approach two

    class Product extends Eloquent{
    
    public function newQuery($excludeDeleted = true){
            return parent::newQuery()->join('metal','id','=','metal.product_id');
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题