Laravel - 按特定标准从数据库获取用户数据

时间:2017-04-11 10:11:05

标签: laravel-5.3

我有一个用户表,用于存储我的用户和应用程序表的名称,用于存储用户生成的所有应用程序...用户进行传输应用程序,应用程序打印在管理员页面上,以便管理员可以知道哪个用户提出了申请。

如何检索应用用户的名称?如何让所有申请面包车的用户?

一位用户有很多管理员,如下所示:

用户模型:

public function admin(){
  return $this->hasMany('Martin\Models\admin');
}

管理模型:

public function application()
{
    return hasMany('Martin\Models\Application');
}

应用程序表架构:

Schema::create('applications', function (Blueprint $table)
{
    $table->increments('id');
    $table->string('user_id')->nullable();
    $table->string('destination');
    $table->date('departure_date');
    $table->integer('Number_of_days_hired');
    $table->timestamp('departure_time')->nullable();
    $table->boolean('approved')->default(0);
    $table->timestamps();
});

1 个答案:

答案 0 :(得分:0)

$applications = Application::all();  //get all applications. Application is your Eloquent model of the Applications table

$userIds = $applications->pluck('user_id'); // get ids from all the users that applied

$names = User::whereIn($userIds)->pluck('name'); // name is equal to the name of the column in database which stores name of the User (you didn't specify that in your question)

foreach($names as $name) {
    // do something with name
}

<强>更新

有两种方法可以找到申请特定内容的用户:

<强> 1。刀片文件:

@foreach($users as $user)
    @if($user->applied_for_van) // put your criteria for van application here
        <td>{{$user->name}}</td>
    @endif
@endforeach

2.1获取所有用户的文件:

$users_who_applied_for_van = [];

foreach($users as $user) {
    if($user->applied_for_van) {
        $users_who_applied_for_van[] = $user; // this equal to array_push. add user to the array basically
    }
}

2.2刀片文件:

    @foreach($users_who_applied_for_van as $user)
        <td>{{$user->name}}</td>
    @endforeach