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

标签 php mysql arrays laravel laravel-5.1

我有一个表列,其中包含用户选择的主题 ID 数组。这些主题及其值还有另一个表。我需要返回与主题列中保存的 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 如何将 ids 数组映射到另一个表中的相应值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32354934/

相关文章:

php - 调用前面带美元符号的函数

javascript - 如何避免用户直接在浏览器中打开弹出窗口?

php - Facebook 爬虫严重攻击我的服务器并忽略指令。多次访问同一个资源

mysql - 带有 "Between dates"的 CakePHP 模型

javascript - 如何读取 angular4 中响应 HTTP 请求而收到的 protobuf 对象

php - 如何在 Volusion API 中编写连接查询

mysql - 计算多列不同值的出现次数

arrays - 从没有循环的两个数组元素成对创建数组

javascript - 计数对象内的数组并替换

MySQL:连接类型的快速分割