表格
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();
如何获得经批准的供应商库存的所有产品?
由于
ķ
答案 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
Products
个Vendor
个已批准的Profile
。