Laravel Eloquent查询生成器(使用查询存在,使用whereHas)

时间:2015-11-06 21:22:01

标签: laravel eloquent query-builder

表格

PROFILE
id    address    type    approved    fky_profile_vendor_id

VENDOR
id    name

PRODUCT
id    name    price    instock    fky_prod_vendor_id

关系

PROFILE <-(one-to-one)-> VENDOR <- (one-to-many) -> PRODUCT

查询

Eloquent查询以获取库存中的所有产品

PRODUCT::where('instock','>',0)->get();

如何获得经批准的供应商库存的所有产品?

由于

ķ

1 个答案:

答案 0 :(得分:0)

应用\资料

use Illuminate\Database\Eloquent\Model;

class Profile extends Model {

    public function scopeApproved($query)
    {
        return $query->where('approved', 'y');
    }

    public function vendor()
    {
        return $this->belongsTo('App\\Vendor');
    }

}

-

应用\卖方

use Illuminate\Database\Eloquent\Model;

class Vendor extends Model {

    public function profile()
    {
        return $this->hasOne('App\\Profile');
    }

    public function products()
    {
        return $this->hasMany('App\\Product');
    }

}

-

应用\产品

use Illuminate\Database\Eloquent\Model;

class Product extends Model {

    public function vendor()
    {
        return $this->belongsTo('App\\Vendor');
    }

}

使用方法:

$vendors = Vendor::whereHas('profile', function ($q) { $q->approved(); })->with('products')->get();

$products = $vendors->map(function ($vendor)
{
    return $vendor->products;
});

这将返回Collection ProductsVendor个已批准的Profile