如何获得某个用户喜欢的图像?

时间:2018-09-03 22:00:55

标签: php laravel eloquent

我正在尝试创建一个变量,该变量包含具有特定ID的用户喜欢的最近7张图像,因此我可以将该变量传递给我的视图。我相信我必须使用whereHas(),但到目前为止,我没有尝试过任何工作,因此我可能做错了。

我的桌子是:

Table: Votes
Columns: id, user_id, image_id, vote

Table: Users
Columns: id, username, password

Table: Images
Columns: id, name, user_id, path

在votes表中,如果vote值为1,则为like,为0,则为dislike。

我有3个表的模型,如下所示:

Image

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }


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


}

用户:

<?php

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;


class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;
    public function images(){

        return $this->hasMany('App\Image');
    }

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

}

投票:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Vote extends Model
{
    public function images(){
        return $this->belongsTo('App\Images');
    }
}

我能够找到与我的想法接近的东西:

$likedImages = Image::where('parent_id', NULL)->whereHas('votes', function($q) use ($vote) {
    return $q->where('vote', $vote);
})->orderBy('created_at', 'desc')->limit(7)->get();

不幸的是,每个人都获得了喜欢的图像,而不仅仅是特定用户。

2 个答案:

答案 0 :(得分:1)

通常whereHas()可以解决这个问题,如果您想对已投票的图像进行类似的操作

Image::whereHas('votes',function($votes) {
    //if you want to get only votes with 1 you do
    $votes->where('vote',1);
})
//if you want to get the latest 7 images you order them and take 7
->orderBy('id','DESC')
->take(7)
->get();

这将为您提供所有包含votes行的图像,如果失败,则可能是您的关系设置不正确。

答案 1 :(得分:0)

您需要使用Vote模型,并获取最近的7票 ,其中like值为1 ,然后LEFT JOIN images表

我不是ORM专家,但是...

一个未经测试的例子:

$votes = Vote::where([
        ["user_id", "=", $userId],
        ["vote", "=", 1]])->leftJoin("images", "user_id", "=", "images.user_id")->latest()->take(7);

再次,这是未经测试的,但是我给了你这个主意。

相关问题