【问题标题】:Laravel - Get articles from feeds for one userLaravel - 从一个用户的提要中获取文章
【发布时间】:2018-03-01 05:12:24
【问题描述】:

我有三张桌子:

文章:

  • 身份证
  • feed_id
  • 标题

供稿:

  • 身份证
  • user_id
  • 姓名

用户:

  • 身份证
  • 姓名

我想从一个用户的提要中获取所有文章,我搜索 Eloquent 关系...

你能帮帮我吗?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    首先,在User 模型上定义关系。适合您情况的最佳选择是使用Has Many Through 关系:

    public function articles()
    {
        return $this->hasManyThrough(
            'App\Article',
            'App\Feed',
            'user_id', // Foreign key on feeds table...
            'feed_id', // Foreign key on articles table...
            'id', // Local key on users table...
            'id' // Local key on feeds table...
        );
    }
    

    然后创建一个用户对象并获取他的文章:

    $user = /App/User::with('articles')->find($id);
    
    foreach($user->articles as $article) {
        // do whatever you need
    }
    

    【讨论】:

    • 我有这个问题,我只有 _id 而不是所有字段... #attributes: array:1 [▼ "_id" => ObjectID {#278 ▼ +"oid": " 59c224a09a89203b6e137622" } ]
    • 这是什么?我的意思是你是怎么得到它的?
    • @CélineMartin 我已经对其进行了测试,并且效果很好。也许你的模型有问题。
    • 所以,我使用 Laravel MongoDB,我的文章是一个 MongoDB 集合,其余的表都在 MySQL 上。文章ID为_id,其余为id。
    • 您也可以通过添加 protected $primaryKey = '_id'; 来更改其模型上的文章的主键;
    【解决方案2】:

    laravel 文档始终是研究的良好开端,请阅读 hasManyThrough https://laravel.com/docs/5.5/eloquent-relationships#has-many-through

    不介意如果是5.5,它们之间没有显着差异

    【讨论】:

      【解决方案3】:

      在模型中

      在 Articles.php 中

      public function Feed()
      {
          return $this->belongsTo('App\Feed');
      }
      

      在 Feed.php 中

      public function User()
      {
          return $this->belongsTo('App\User');
      }
      
      public function Articles()
      {
          return $this->hasMany('App\Articles');
      }
      

      在 User.php 中

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

      在控制器中

      //获取id = $id的用户的所有文章

      $reports2 = Articles::with(array('Feed'=>function($query)use($id){
          $query->with('User');
          $query->where('user_id',$id);
      }))->orderBy('id', 'desc')
          ->get();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-02
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        • 2014-09-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多