如果列值存在于主模型或 Eloquent 中的关系中,我如何 select 一行
How can I select a row if a column value is present on the main model or the relation in Eloquent
如果一个 "product" 模型的字段代码与 "variation" table 也有一个代码字段具有一对多关系。如果任一 table 的代码值具有某些值,我如何使用 eloquent 到 select 行。
我怎么能这样做:
select * from product inner join variation on product.id = variaction.product_id where product.code = "code" or variation.code = "code".
考虑您的产品和变体模型如下所示:
class Product extends Model
{
protected $table = 'product';
public function variation()
{
return $this->belongsTo('App\Variation', 'product_id', 'id');
}
}
class Variation extends Model
{
protected $table = 'variation';
public function products()
{
return $this->hasMany('App\Product', 'id', 'product_id');
}
}
你可以像这样用Eloquent获取数据:
$code = 'code';
Product::where('code', '=', $code) // for product table
->orWhereHas('variation', function($query) use ($code) {
$query->where('code', '=', $code); // for variation table
});
如果一个 "product" 模型的字段代码与 "variation" table 也有一个代码字段具有一对多关系。如果任一 table 的代码值具有某些值,我如何使用 eloquent 到 select 行。
我怎么能这样做:
select * from product inner join variation on product.id = variaction.product_id where product.code = "code" or variation.code = "code".
考虑您的产品和变体模型如下所示:
class Product extends Model
{
protected $table = 'product';
public function variation()
{
return $this->belongsTo('App\Variation', 'product_id', 'id');
}
}
class Variation extends Model
{
protected $table = 'variation';
public function products()
{
return $this->hasMany('App\Product', 'id', 'product_id');
}
}
你可以像这样用Eloquent获取数据:
$code = 'code';
Product::where('code', '=', $code) // for product table
->orWhereHas('variation', function($query) use ($code) {
$query->where('code', '=', $code); // for variation table
});