[英]Display other table data from drop down list when edit
Is that possible to get data from other table? 是否可以从其他表获取数据?
Let say in create table, I get all the info from genre table and display all data in drop down list 假设在创建表中,我从类型表中获取所有信息,并在下拉列表中显示所有数据
<select name="mov_genre" id="mov_genre" class="form-control input-sm">
<option value="">类型</option>
@foreach(App\Genre::all() as $gData)
<option value="{{$gData->gen_title}}">{{$gData->gen_title}}</option>
@endforeach
</select>
In edit page, I want to display it as well but how to display it as the genre I selected when create? 在编辑页面中,我也要显示它,但是如何将其显示为创建时选择的类型?
In my opinion, you should use $gData->id
as value
of each option. 我认为,应该将$gData->id
用作每个选项的value
。 Because normally you store the id
as foreign key and not something like the title. 因为通常您将id
存储为外键而不是标题。
But to your question itself: You can simply add an if
statement that checks within the foreach
loop if the current item is the selected one. 但是对于您自己的问题:您可以简单地添加一个if
语句,该语句在foreach
循环中检查当前项是否为选定项。 In my example I assume you have a variable $movie
which is the entry you want to edit. 在我的示例中,我假设您有一个变量$movie
,这是您要编辑的条目。
<select name="mov_genre" id="mov_genre" class="form-control input-sm">
<option value="">-- SELECT GENRE --</option>
@foreach(App\Genre::pluck('gen_title', 'id') as $key => $value)
<option value="{{ $key }}" {{ optional($movie)->genre_id === $key ? 'selected' : '' }}>{{ $value }}</option>
@endforeach
</select>
Please note that I swapped App\\Genre::all()
for App\\Genre::pluck('gen_title', 'id')
. 请注意,我将App\\Genre::all()
换为App\\Genre::pluck('gen_title', 'id')
。 This will only load the both fields gen_title
and id
and put them in an array where id
is the key and gen_title
the value. 这将只加载gen_title
和id
这两个字段,并将它们放在一个数组中,其中id
是键, gen_title
是值。 It is done for better performance as we do not load unnecessary data. 这样做是为了提高性能,因为我们不会加载不必要的数据。
Also note that optional($movie)
will return null
when $movie
is not set. 另请注意,未设置$movie
时, optional($movie)
将返回null
。 This is done to reduce weird if
statements and is common practice. 这样做是为了减少怪异的if
语句,这是常见的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.