douxianglu4370 2016-03-31 10:30
浏览 19

使用Eloquent&Laravel访问特定列

I'm teaching myself Laravel by building an application that, amongst other things, fetches data from default Wordpress tables, and I've run into a best-practices question that I'm not sure how to tackle.

I've got a very simple model for the User database that looks like this:

namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    public $table='wp_users';
    protected $primaryKey='user_id';
}

And I'm able to fetch it into an array using a line like $users = User::all(); in my controller that I can then send into my view in any number of different ways.

Now; my question for best practices has to do with accessing multiple values from a particular column or from a set of columns from the database on a website.

Say I want to create a dropdown list that contains the display_name from the database as the ... well, displayed text, and the user_login as the option value that gets passed in the form.

In the "good old" days, I could do this with something like a foreach statement that pushes <?php echo $whatever; ?> into the relevant places in the html, but it's a very ugly solution. I mean ... just look at this stuff:

<?php foreach ($users as $key => $value) {
    echo "<option value='" . $key . "'>" . $value['name'] . "</option>";
} ?>

Using Eloquent, I could do something like Form::select('size', array('L' => 'Large', 'S' => 'Small')), and I'm sure there's a way of passing an array into this statement, but that's exactly my problem ... I just can't seem to figure out how to do it. How do I tell the Form statement to use $users[0]->display_name for the first entry, $users[1]->display_name for the second, etc... ?

  • 写回答

3条回答 默认 最新

  • doulingzhuang3079 2016-03-31 10:34
    关注

    in your controller do

    $users = User::get()->pluck('name','user_id');
    

    in your form

    Form::select('size', $users)
    

    This will simply build your dropdown list for you.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度