Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Take two.</p> <p>in Device.php:</p> <pre><code>// creates a users property within a Device, a container of associated Users public function relations() { return array( 'users'=&gt;array(self::MANY_MANY, 'User', // don't use HAS_MANY 'user_devices(user_id, device_id)'), // composite key assumed ); } </code></pre> <p>then to find if the requested device is owned by the requesting user:</p> <pre><code>$device = Device::model()-&gt;findByPk($deviceId); if ( $device-&gt;users-&gt;findByPk($userId) == Null ) $device = Null; </code></pre> <p>It seems like this would work but inefficiently retrieve a lot of unneeded User records, since you already know who the user is and likely already have their activeRecord. To avoid this innefficiency, the Yii Agile Development book uses raw SQL for M2M relationship queries within the parent model (Device.php):</p> <pre><code>// "Agile" uses a $user AR argument, you can use $userId instead public function doesUserOwnDevice($userId) { $sql = "SELECT user_id FROM user_devices WHERE device_id=:deviceId AND user_id=:userId"; $command = Yii::app()-&gt;db-&gt;createCommand($sql); $command-&gt;bindValue(":deviceId", $this-&gt;id, PDO::PARAM_INT); $command-&gt;bindValue(":userId", $userId, PDO::PARAM_INT); return $command-&gt;execute()==1 ? true : false; } </code></pre> <p>I used <code>Device</code> rather than <code>Devices</code> for the name of the model (likewise <code>device</code> for the name of the table). Refactor if you cut and paste. Likewise for <code>User</code>. Likewise for missing "tbl_" prefix.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload