如何根据id获取国家名称?

我有一张表,我在其中保存语言的记录 ID ( language_skills_selected)。现在,我需要为每个项目获取名称。我将名称保存在 table 中language_skills。


这是我的变量和每个人的dd:


$data['user_test'] = DB::table('language_skills_selected')->where('user_id', $id)->get();


Language: 22 - Level: Intermediate 


Language: 41 - Level: Beginner 


Language: 13 - Level: Expert 


Language: 35 - Level: Expert 


Language: 23 - Level: Intermediate 

在这里我有名字的变量: $data['language_skills'] = \App\LanguageSkill::lists('language_skill','id');


{"1":"Albanian","2":"Arabic","3":"Bengali","4":"Belarus","5":"Bulgarian","6":"Czech","7":"Chinese","8":"Korean","9":"Croatian","10":"Danish","11":"Hebraic","12":"English","13":"Estonian","14":"Finnish","15":"French","16":"German","17":"Greek","18":"Hindi","19":"Icelandic","20":"Italian","21":"Japanese","22":"Latvian","23":"Lithuanian","24":"Macedonian","25":"Hungarian","26":"Norwegian","27":"Dutch","28":"Persian","29":"Polish","30":"Portuguese","31":"Romanian","32":"Russian","33":"Serbian","34":"Slovak","35":"Slovene","36":"Spanish","37":"Swedish","38":"Thai","39":"Turkish","40":"Ukrainian","41":"Other"}

所以,而不是这些 id,我需要有语言名称 - 例如:Language: Bulgarian - Level : Expert


红糖糍粑
浏览 133回答 3
3回答

白衣染霜花

请试试这个$data['user_test'] = DB::table('language_skills_selected')      ->select("language_skills.language_skill")      ->join("language_skills","language_skills_selected.language_skills","=","language_skills.id")      ->where('language_skills_selected.user_id', $id)->get();

qq_花开花谢_0

你可以使用这个代码1 -> query for Get All skills$data['user_test'] = DB::table('language_skills_selected')->where('user_id', $id)->get();2 -> Query For language_skills Name$data['language_skills'] = \App\LanguageSkill::where('id',$data['user_test']['language_skills])->get('language_skills');3 -> Set Name instead of ID$data['user_test']['language_skills'] = $data['language_skills'];您可以使用 foreach 循环;我建议更改变量的名称

手掌心

命名约定首先,我会改变结构以使用传统的 Laravel 命名。它还可以帮助其他人更好地理解表中的关系。您已经将id其用作自动增量主键,这很好。如果您随后通过外键引用另一个表,请使用单数表名,后跟_id. 所以你的language_skills_selected表结构变成language_skills_selectedid int primaryuser_idint 外键(用户表)language_skill_idint 外键(language_skills 表)language_skillsid int 主要name字符串(名称,单数,因为其中只有一个名称)我会将列重命名language_skills为name,因为表名已经表明表中的每个条目都是语言技能。列名应该更能描述它实际包含的内容,在您的情况下,language_skills列包含名称。因此,您不妨以这种方式命名该列。连接表在 Laravel 中,您可以使用查询构建器 (参见此处)来构建查询,或者您可以使用Eloquent 模型(参见此处)。我强烈建议您仔细阅读文档的两个部分。它是框架的重要组成部分,选择何时使用取决于您的用例。现在终于到了你的解决方案。如果您更改了列名,则可以在两个表之间编写连接语句,如下所示:$data['user_test'] = DB::table('language_skills_selected')     ->join('language_skills', 'language_skills_selected.language_skill_id', '=', 'language_skills.id')     ->where('user_id', $id)     ->get();然后,您将获得一个连接结果,您也可以在其中访问 language_skill 的名称。我还建议您总体上阅读更多有关 MySQL 的信息,因为在深入了解该框架之前,这是一个很好的基础知识。查找 MySQL 连接,并阅读这样的材料。
打开App,查看更多内容
随时随地看视频慕课网APP