Laravel Eloquent Query Builder(使用查询存在,使用whereHas)
Laravel Eloquent Query Builder (Using query existence, using whereHas)
表格
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();
我怎样才能获得认可供应商的所有库存产品?
谢谢
K
App\Profile
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');
}
}
--
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');
}
}
--
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;
});
这将 return Collection
的 Products
的 Vendor
获得批准 Profile
。
表格
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();
我怎样才能获得认可供应商的所有库存产品?
谢谢
K
App\Profile
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');
}
}
--
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');
}
}
--
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;
});
这将 return Collection
的 Products
的 Vendor
获得批准 Profile
。