[Yii 2]: come si fa una relation hasOne con condizioni?

Tabelle:

Products: id, name

Datasheet: id, product_id, name

In questo specifico caso ciascun prodotto può avere zero o al massimo un datasheet.

Ho bisogno di ottenere i prodotti che NON hanno un datasheet.

Vorrei usare dentro al modello di datasheet una relation di tipo ‘hasOne’ ma non ho capito come indicare, a parte la relazione product_id -> id, che voglio solo quelli dove datasheet.id IS NULL

Per ora ho creato la relation dentro a datasheet ed ho provato a fare quello che dovrebbe essere l’equivalente di uno scope di Yii 1




namespace frontend\models;


use yii\db\ActiveQuery;


class Product extends \common\models\Product

{


    /**

     * @return \yii\db\ActiveQuery

     */

	public function getDatasheet()

	{

		return $this->hasOne(Datasheet::className(), ['datasheet_id' => 'id'] );

	}


	public function getWithoutDatasheet()

	{


		return new ActiveQuery()

					->joinWith('datasheet')

				        ->andWhere([

				    	  'datasheet.id' => null,

        				  'product.category_code != "G00"'

				   	]);


	}


}



Ho provato da usarlo cosi:




$products_without_datasheet = Product::find()->withoutDatasheet()->all();



ma ottengo

riferito alla riga che ritorna la nuova ActiveQuery

Ti sei ricordato di fare l’override del metodo find nella classe \common\models\Product?


public static function find()

{

    return new frontend\models\Product(get_called_class());

}

C’e’ un problema di sintassi php. Questa sintassi e’ scorretta:


    return new ActiveQuery()

        ->joinWith('datasheet')

        ->andWhere([

            'datasheet.id' => null,

            'product.category_code != "G00"'

        ]);

prova a correggerla in questo modo:


    return (new ActiveQuery())

        ->joinWith('datasheet')

        ->andWhere([

            'datasheet.id' => null,

            'product.category_code != "G00"'

        ]);