title: Yii2 validate existencies in model
body: <p>For my software, I have to prevent a user from selling more stocks than they find in the database, so to start, I have the stock field set as an unsigned integer.</p>
  
  <p>The problem is that although these units cannot be sold and subtracted, the sale is generated without stock, because it is not validated.</p>
  
  <p>To make the sale, I have three models corresponding to three tables in the database: Stock, detail of sale and sale.</p>
  
  <p>To validate, create some functions so that the registered data of the tables are found in the database as follows:</p>
  
  <pre><code>public function getDetails()
  {
      return $this-&gt;hasOne(Articledetail::className(), ['ID_ARTICLE_DETAIL' =&gt; 'ID_ARTICLE_DETAIL']);
  }
  
  public function getExistences()
  {
      if ($mother = Articledetail::findOne($this-&gt;mother))
      {
          return $mother-&gt;details-&gt;ARTICLE_STOCK;
      }
  }
  </code></pre>
  
  <p>Then, it should be possible to validate the model with the following rule:</p>
  
  <pre><code>public function rules()
  {
  
      return [
          ['STOCK', 'compare', 'compareAttribute' =&gt; 'existences', 'operator' =&gt; '&lt;='],
      ];
  }
  </code></pre>
  
  <p>The problem is that I think that you are not getting the integer value of the table in the database, because in the form, it doesn't matter what value you enter, it always says that it must be less than or equal to the existences function.</p>