title: Yii2 REST api conditional call to relational class
body: <p>it's my first post here, so apologies if I transgress any rules.</p>
  
  <p>Here I am, setting up an angular application based on a RESTful Yii2 API.
  So, I have a little problem that I cannot seems to solve. 
  I have 3 classes: event, user, and participation. A user can participate to 0,n event. 
  So in my "view" action of the user controller in my api, I have to return a JSON formatted user object like the following:</p>
  
  <pre><code>[{
  "user_id":5,
  "userGroup_id":1,
  "user_login":"demo",
  "participations":
      [
      {"event":{event_id:1,event_name:"test"},
       "user_id":5,
       "Droit_id":30
       },
      {"event":{event_id:2,event_name:"test2"},
       "user_id":5,
       "Droit_id":10
       }
      ]
   }]
  </code></pre>
  
  <p>On the other hand, when i'm in the event contoller, I'd like to do the opposite:</p>
  
  <pre><code>[{
  "event_id":1,
  "event_name":"test",
  "participations":
  [{
      "event_id": 1,      
      "user":{user_id:5,user_login:"demo"},
      "Droit_id":30
  },
  {
      "event_id": 5,  
      "user":{user_id:6,user_login:"demo2"},
      "Droit_id":10
  }]
  </code></pre>
  
  <p>}]</p>
  
  <p>So I could setup my "participation" model so it would return the user and the event each time, with the "fields()" function, but I don't want to.
  I want the model "participation" to have a field "user" when called from a "event" and vice-versa, not both at the same time ( I don't need the event to be returned when I'm already in the event ).</p>
  
  <p>I use <code>"use yii\rest\Controller;"</code> and 
         <code>$behaviors['contentNegotiator'] = [
              'class' =&gt; ContentNegotiator::className(),
              'formats' =&gt; [
                  'application/json' =&gt; Response::FORMAT_JSON,
              ],
          ];</code>
  to make every output JSON formatted.</p>
  
  <p>Here's my view action:</p>
  
  <pre><code>$query = User::find()-&gt;where(['user_id' =&gt; $id])-&gt;with('participations');
      return new ActiveDataProvider([
          'query' =&gt; $query,
      ]);
  </code></pre>
  
  <p>This output </p>
  
  <pre><code>[{
  "user_id":5,
  "userGroup_id":1,
  "user_login":"demo",
  "participations":
      [
      {"event_id":1,"user_id":5,"Droit_id":30},
      {"event_id":2,"user_id":5,"Droit_id":10}
      ]
  }]
  </code></pre>
  
  <p>I tried "with('participations.event');" but doesn't work.
  My relations are all correctly set up</p>
  
  <p>Any Ideas?</p>