【问题标题】:Get all posts and check if user liked each post获取所有帖子并检查用户是否喜欢每个帖子
【发布时间】:2015-06-25 20:14:43
【问题描述】:

我正在尝试创建一个 Eloquent 查询来获取所有帖子并检查用户是否喜欢这些帖子。

我有以下型号:

Post.php

class Post extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'posts';

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function likes()
    {
        return $this->hasMany('Like');
    }
}

Like.php

class Like extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'likes';
}

还有你典型的User 模型。

我的数据库结构如下:

posts表:

+----+---------+---------+
| id | user_id | message |
+----+---------+---------+

users表:

+----+----------+
| id | username |
+----+----------+

likes表:

+----+---------+---------+
| id | post_id | user_id |
+----+---------+---------+

目前,我的查询只返回所有帖子,但我如何修改它以返回所有帖子检查用户是否喜欢每个帖子?

Route::get('/', array('as' => 'index', function()
{
    $posts = Post::all();

    return View::make('index')->with('posts', $posts);
}));

谢谢!

【问题讨论】:

  • 您需要在每个帖子的基础上执行此操作。或者使用连接等创建自定义原始查询。

标签: laravel laravel-4 eloquent


【解决方案1】:

posts 表和 likes 表之间的左连接怎么样,通过实际用户的 id 过滤?

$post = DB::table('post')
                 ->select(DB::raw('message, likes.user_id IS NOT NULL as liked'))
                 ->leftJoin('likes', 'users_id', '=', 'likes.user_id')
                 ->where('likes.user_id', '=', $curent_user_id)  
                 ->get();

我现在没有办法测试它,但我希望它能给你一些启发:)

【讨论】:

    【解决方案2】:

    您可以使用该特定用户的帖子获取likes。试试这个..

    Post::with(['likes' => function() use ($user_id) { $q->where('user_id','=', $user_id); }])->all();
    

    如果用户不喜欢该帖子,它将返回空白数组。

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      相关资源
      最近更新 更多