我有一个表格列,其中包含用户选择的主题 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/