Fetch specific fields on a hasMany relation

前端 未结 2 1206
天涯浪人
天涯浪人 2021-02-04 02:26

I have a hasMany relation function like this:

public function articles()
{
    return $this->hasMany(\'App\\Article\');
}

A

相关标签:
2条回答
  • 2021-02-04 03:11

    Yes, it's possible. You've got a couple options.

    *NB: For options 1 and 2 below, the foreign key (user_id) must be selected so that Laravel knows how to link the models together when building the relationships.

    1. Modify the relationship query when using it. The with() method can accept an array of key/value pairs where the key is the name of the relationship and the value is a Closure that modifies the relationship query.

       $data = \App\User::with(['articles' => function($query) {
           // user_id is required here*
           $query->select(['id', 'title', 'user_id']);
       }])->get();
      
    2. Create a new relationship that contains the fields you want.

       public function articleTitles() {
           // user_id is required here*
           return $this->hasMany('App\Article')->select(['id', 'title', 'user_id']);
       }
      
       $data = \App\User::with('articleTitles')->get();
      
    3. If you're only concerned about the array/json output, you can modify the App\Article model to only display the id and title when converted to an array.

       class Article extends Model {
           protected $visible = ['id', 'title'];
       }
      

    What you choose depends on what you need.

    0 讨论(0)
  • 2021-02-04 03:13
    $data = \App\User::with('articles:id,title,user_id')->get();
    

    // user_id is important in hasmay relationships

    0 讨论(0)
提交回复
热议问题