【问题标题】:laravel retrieving data from databaselaravel 从数据库中检索数据
【发布时间】:2017-03-15 11:31:16
【问题描述】:

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

注意模型:

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'));

}

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

【问题讨论】:

  • 添加where类
  • 可能类似于$pilotNotes = Pilot::find($id)->note();,其中$id 是您想要获取其笔记的用户(Pilot)的ID

标签: php mysql laravel


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这要容易得多:

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

    $id 是 Pilot id,可能是也可能不是函数参数。

    另一种方式是:

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

    【讨论】:

    • SQLSTATE[42S22]:未找到列:1054 'where 子句'中的未知列'notes.pilot_id'(SQL:select * from notes where notes.pilot_id = 5 和notes.pilot_id 不为空)
    • 我的表看起来像,Pilot 表:id、电话、电子邮件。备注表:id、日期、备注
    • @tomczas note 表中没有外键?
    • 否则你怎么知道这张纸条属于哪个飞行员?
    【解决方案3】:

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

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

    $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
    

    【讨论】:

    • 但是在我的笔记表中我没有 Pilot_id 我应该添加它吗?
    • @tomczas 是的,你应该添加它并添加belongsTo() 关系。
    • @tomczas 还请注意,如果您已经知道飞行员的 ID,并且只想获得一份飞行员的笔记,我的代码将只创建一个对 DB 的查询,而其他人的解决方案将创建两个。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-19
      • 2013-05-15
      • 2021-09-24
      • 2021-01-18
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      相关资源
      最近更新 更多