[英]Is there a proper way to cross join using yii2?
我正在查詢activedataprovider,將其用於搜索目的。 我需要使用交叉聯接。 我使用了joinWith,但是它抱怨倉庫模型與產品沒有關系。 這是產品。 因為這是交叉聯接,所以在這附近有什么工作可以避免觸發關系嗎?
其他說明:在基於倉庫的原始模型中,諸如product_id,product.category等某些屬性不存在。 如果我僅添加公共屬性/屬性變量還是需要變通解決方案,它會即時運行嗎?
public function search($params)
{
$query = Warehouse::find()->joinWith('product')
->select(['product_id' => 'product.id','warehouse.warehouse', 'product.category', 'product.product', 'min_stock' => 'coalesce(critical.min_stock, -1)'])
->leftJoin('critical', 'critical.product_id = product.id AND critical.warehouse_id = warehouse.id')
->where(['warehouse.id' => $this->_id]);
$this->load($params);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere(['category' => $this->category]);
$query->andFilterWhere(['like', 'product', $this->product]);
return $dataProvider;
}
對於所有難以(或不可能)使用yii2 activeRecord或activeQuery功能構建的查詢,可以使用findBySql
$sql = "select
product.id as id
, warehouse.warehouse as warehouse
, product.category as category
, product.product as product
, coalesce(critical.min_stock, -1) as min_stock
from Warehouse
cross join product
left join critical on ritical.product_id = product.id AND critical.warehouse_id = warehouse.id
where warehouse.id' = " . $this->_id
$model = Warehouse::findBySql($sql );
將查詢記錄獲取為數組,因此您無需定義關系
public function search($params)
{
$query = Warehouse::find()->joinWith('product')
->select(['product_id' => 'product.id','warehouse.warehouse', 'product.category', 'product.product', 'min_stock' => 'coalesce(critical.min_stock, -1)'])
->leftJoin('critical', 'critical.product_id = product.id AND critical.warehouse_id = warehouse.id')
->where(['warehouse.id' => $this->_id]);
$query = Warehouse::find()
->select('product.id as id,warehouse.warehouse as warehouse, product.category as category, product.product as product, coalesce(critical.min_stock, -1) as min_stock ')
->leftJoin('product', 'warehouse.product_id = product.id')
->leftJoin('critical', 'critical.product_id = product.id')
->where(['warehouse.id' => $this->_id]);
->andWhere('critical.warehouse_id = warehouse.id')
->asArray();
$this->load($params);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere(['category' => $this->category]);
$query->andFilterWhere(['like', 'product', $this->product]);
return $dataProvider;
}
現在,您將獲得記錄作為數組而不是對象。
第二種方法是,使用hasOne()
或hasMany()
在模型中定義倉庫與產品之間的關系
-> joinWith('product',true,'交叉連接')
public function getProduct()
{
return $this->hasOne(Product::className(), []);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.