php - Laravel Eloquent 中的 If 语句

标签 php mysql laravel eloquent

我有两个模型,它们通过三个 ID 连接到一个 1 ID。模型 AdviceProtocol 定义了三个 id:threshold_category1_idthreshold_category2_idthreshold_category3_id。这三个都链接到模型 Categories 中的 id。 threshold_cateogry_id 可以是链接到 categories.id 的数字,也可以是 null。

在我的查询中,我需要检查三个 threshold_catogory_ids,如果它们是 NOT NULL,则检索 categories.name。我现在的查询:

$advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.name', 'advice_protocols.category', 'questions.name AS question_name', 'categories.name as Category_Name','categories.name as Category_Name2'])
            ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
            ->join('categories', function ($join)
            {
                $join->on('advice_protocols.threshold_category1_id', '=', 'categories.id')->orOn('advice_protocols.threshold_category2_id', '=', 'categories.id')->orOn('advice_protocols.threshold_category3_id', '=', 'categories.id');
            })

此查询现在两次返回相同的 category.name。 我试图查看其他人如何解决这个问题,但我无法在网上找到准确的信息。

最佳答案

我会尝试使用三个不同的别名进行三个连接,然后获取每个不同别名的每个类别名称的名称:

$advicePreparationsQuery = AdviceProtocol::select(['advice_protocols.name', 'advice_protocols.category', 'questions.name AS question_name', 'categories1.name as Category_Name','categories2.name as Category_Name2','categories3.name as Category_Name2'])
            ->join('questions', 'advice_protocols.user_goal_id', '=', 'questions.id')
            ->join('categories as categories1', 'advice_protocols.threshold_category1_id', '=', 'categories1.id')
            ->join('categories as categories2', 'advice_protocols.threshold_category2_id', '=', 'categories2.id')
            ->join('categories as categories3', 'advice_protocols.threshold_category3_id', '=', 'categories3.id');

关于php - Laravel Eloquent 中的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42550295/

相关文章:

mysql - 在oracle中将列转换为varchar,即mysql longtext

laravel - xdebug、PhpStorm 和 Laravel 3/mod_rewrite 未命中断点

php - 如何对 URL 中未知数量的参数使用 laravel 路由?

php - 如何从重复行检查 MYSQL 连接中的一个特定结果

PHP 删除 HTTP header

mysql - 使用连接两个表从一个表中删除

laravel - 传递给 App\Mail\SurveyMail::__construct() 的参数 1 必须是 App\Mail\User 的一个实例,数组给出

php - 需要帮助让 Fine Uploader PHP 服务器示例正常工作

PHP 包含多个文件的性能

mysql - 字符串分类策略