laravel fetch下拉查询模型中的数据值

时间:2017-12-20 06:33:50

标签: php laravel

我有一个表单,并且有一个下拉列表。在视图页面中,我想从模型中获取数据。

模型功能

 public static function allVenueClientList() {

        /* Also if possible i want to add ($users = DB::table('clients') join query on this query which is already working for me.

        return Client::where('type', static::CLIENT_TYPES['Venue'])
        ->orWhere('type', static::CLIENT_TYPES['Both'])
        ->pluck('name', 'id')->all();

        */

        $users = DB::table('clients')
        ->join('users', 'clients.id', '=', 'users.user_id')
        ->where('users.status', '=', 'Active')
        ->where('users.id', '!=', '1')
        ->select('clients.name', 'clients.id')
        ->get();
        return $users;
}

我的观看页面代码:

<div class="form-group{{ $errors->has('client_id') ? ' has-error' : '' }}">
{{Form::label('client_id', trans('admin.venue.fields.client_id'),['class' => 'col-md-4 control-label'])}}
<div class="col-md-6">
    {{Form::select('client_id',[0 => trans('admin.venue.select.client_id')] + \App\Client::allVenueClientList(), old('client_id', isset($venue) ? $venue->client->id : 0), ['class' => 'form-control select'])}}
    @if ($errors->has('client_id'))
        <span class="help-block">
            <strong>{{ $errors->first('client_id') }}</strong>
        </span>
    @endif
</div>

如果可以按第二次查询更改第一个查询,那么如何在此下拉列表中获取$ users数据?

2 个答案:

答案 0 :(得分:0)

在定义上述模型函数的控制器函数内部,使用紧凑数据传递数据......

        like this $compactdata= your query result.
       return view('your view', compact('compactdata'))

然后在视图中循环结果如果它是其他方面的集合只是在视图中显示结果,如上所述。 请检查语法错误。我不确定语法。

答案 1 :(得分:0)

我承认并不完全理解这个问题,但我的回答太大而无法发表评论。

听起来你想将其中的一部分卸载到脚本中。

脚本:

function usersearch(client_id)
{
        $.post('usersearch', {
             _token: $('meta[name=csrf-token]').attr('content'),
             client_id: client_id,
         }
        )
        .done(function(data) {
                document.getElementById('myotherdropdown').innerHTML = data;
        })
        .fail(function() {
            alert( "I did an oops" );
        });
}

然后当前的选择获得一个事件

<select name="client_id" onchange=usersearch(this.value)>
web.php中的

Route::post('/usersearch', 'JavaController@usersearch');
JavaController中的

public function usersearch()
{
    $sku = Request::get('client_id');
    $options = '';

    $result = whatever you need to do here;

    foreach($result as $row) {
        $options .= "<option value=\"".$row->user_id."\">".$row->user_name."</option>";
   }

    return $options;
}

显然,考虑到你的设置,事情并不完全如此,但这个想法本身似乎就是你想要的。

如果你真的想要,你甚至可以在脚本中抛出令牌以获得额外的安全性。

$.post('usersearch', {
 _token: $('meta[name=csrf-token]').attr('content'),
 client_id: client_id,
}

希望这就是你所要求的。

相关问题