mysql - 如何仅将没有加入记录的模型添加到集合中 - Eloquent

标签 mysql laravel join laravel-5 eloquent

在我的模型问题中,我与立场有简单的关系

public function standpoints_byrel()
{
//    return $this->hasMany('App\Models\Standpoint');
return $this->hasMany('App\Models\Standpoint',  'question_id');

}

现在, 我还有另一个模型Userattitude(表user_attitudes`),它允许用户对立场投赞成票和反对票。

我可以列出由给定用户投票的立场:

    $user_attitudes = Userattitude::join('entitystandpoints', function ($q) use($questionid,$user) {
        $q->where('user_attitudes.item_type', '=', 'entitystandpoint');
        $q->on('user_attitudes.item_id', '=', 'entitystandpoints.id');
        $q->where('entitystandpoints.question_id', '=', $questionid);
        $q->where('user_attitudes.creator_id','=', $user);
    })
    ->select('user_attitudes.*')
    ->get();

待办事项

现在我尝试列出所有未由给定用户投票的观点。 我不知道如何使用 Eloquent 来做到这一点。 任何帮助表示赞赏。

编辑

满足条件: 如果用户投票赞成或反对,则会创建一个新模型 Userattitude。因此,未投反对票或赞成票的立场模型没有任何可加入的内容。尽管如此,在 Userattitude 中有两个用于投票的字段:“attitude”和“importance”。通常其中之一为空

最佳答案

尝试使用左连接,其中连接的左参数为空。 像这样的东西(但请检查语法,我不是 Eloquent 专家):

   $user_attitudes = Userattitude::leftJoin('entitystandpoints', function ($q) use($questionid,$user) {
        $q->where('user_attitudes.item_type', '=', 'entitystandpoint');
        $q->on('user_attitudes.item_id', '=', 'entitystandpoints.id');
        $q->where('entitystandpoints.question_id', '=', $questionid);
        $q->where('user_attitudes.creator_id','=', $user);
    })
    ->whereNull('entitystandpoints.id')
    ->select('user_attitudes.*')
    ->get();

请告诉我。

关于mysql - 如何仅将没有加入记录的模型添加到集合中 - Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35267340/

相关文章:

mysql - 从链接表中获取论坛主题信息中的用户名

api - Laravel API测试-如何测试具有外部API调用的API

php - 从 Laravel 中的相同方法存储/更新多行

c# - 加入等于一侧的比较键(startswith)

php - 使用 <input type ="button"> 提交表单

php - 在 SQL 循环和输出文件中创建 "blocks"

mysql - 数据库架构建议

javascript - 保护我的私有(private) API

sql - 是否可以在FOREIGN KEY的子表中插入行?

sql - 带有 Join 和 where 子句的 Count 语句