laravel从数据库中检索数据

时间:2017-03-15 11:31:17

标签: php mysql laravel

如何检索属于用户的数据?

注意型号:

class Note extends Model
{
  protected $table = 'notes';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'data', 'zadanie', 'uwagi',
    ];

    public function pilot() {
      return $this->belongsTo(Pilot::class);
    }
}

试点模式:

class Pilot extends Model
{
  protected $table = 'pilots';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'phone', 'email',
    ];

    public function note() {
      return $this->hasMany(Note::class);
    }
}

控制器:

public function show($id)

{

    $notes = Note::with('pilot')->get();


    return view('dziennikpracy.show',compact('notes'));

}

目前它显示所有笔记,我希望它只显示属于每个用户的笔记,我不知道如何做。

4 个答案:

答案 0 :(得分:1)

添加whereHas Note::whereHas('pilot', function($q) use ($userId) { $q->where('user_id', $userId) })

答案 1 :(得分:1)

这样做容易得多:

$notes = Pilot::find($id)->notes()->get(); 

$id是导频ID,可能是也可能不是函数参数。

另一种方式是:

$pilotWithNotes = Pilot::with("notes")->find($id);

答案 2 :(得分:0)

  

我想只显示属于每个用户的笔记

要获得一名飞行员的记录,请执行以下操作:

$notes = Note::where('pilot_id', $pilotId)->get();

要获得所有飞行员的记录,请执行以下操作:

$pilots = Pilot::with('notes')->get();

要显示所有飞行员及其笔记,请在视图中使用嵌套foreach

@foreach ($pilots as $pilot)
    {{ $pilot->name }}
    @foreach ($pilot->notes as $note)
        {{ $note->name }}
    @endforeach
@endforeach

答案 3 :(得分:0)

您的查询可能会返回数据集合,因此您可以“groupBy()”收集方法。