php - Laravel 5.1 如何将一个 id 数组映射到另一个表中的对应值?

标签 php mysql arrays laravel laravel-5.1

我有一个表格列,其中包含用户选择的主题 ID 数组。这些主题及其值(value)还有另一个表格。我需要返回与主题列中保存的 id 对应的值。为了更清楚,假设用户从 34 个主题中选择了 5 个主题,并且相应的 id 以如下字符串形式保存在主题列中:2,5,11,21,23
这些数字中的每一个都对应于主题表中主题的 ID。

    //This is the subjects table
public function up()
    {
        Schema::create('subjects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('subject', 20);
            $table->timestamps();
        });
    }
//and this is the user_info table
 public function up()
    {
        Schema::create('user_info', function (Blueprint $table) {
    ...
    $table->string('subjects');
    ...
     });
    }

如何将一组主题值返回到 View ?

最佳答案

// Find whichever user
$user = \App\User::find(1);

// Convert the string of subjects from a string to an array
$subjectIds = explode(',', $user->subjects);

// Load all subjects which match the ids within the subjectIds array
$subjects = \App\Subjects::whereIn($subjectIds)->get();

// Do something with the subjects
foreach($subjects as $subject) {
   // Output the subject name 
   var_dump($subject->name);
}

关于php - Laravel 5.1 如何将一个 id 数组映射到另一个表中的对应值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32354934/

相关文章:

PHP代码没有被执行,但代码显示在浏览器源代码中

php - 内连接与 3 个表的计数

php - 如何将数组转换为 SimpleXML

javascript - 使用 Ajax 将数组从 javascript 发布到 php 函数

javascript - 清理数值数组中的未定义项目,然后按javascript对其进行排序

php - 初学者 MySQL 数据库搜索 - 没有得到结果

php - 如何在php的编辑页面中选中单选按钮?

php - 从 MySQL 订单中订购

php - 将复选框数据从表单传递到mysql数据库

MySQL 存储过程 - 嵌套循环出错?