簡體   English   中英

Laravel 5.8雄辯的查詢

[英]Laravel 5.8 Eloquent querying

我知道所有Eloquent模型查詢都在Laravel文檔中,並且我已經閱讀了它們以弄清楚這一點,但似乎無法解決。 我正在構建一個食譜應用程序,並且我想基於上載的食譜訪問用戶的特定個人資料圖片。

我有一個由各種用戶上傳的食譜網格。 用戶和配方模型如下。

用戶模型

public function recipes()
{
    return $this->hasMany('App\Recipe');
}

配方模型

public function user()
{
    return $this->belongsTo('App\User');
}

在我的配方網格中,我在配方卡中包含以下代碼。

索引刀片/視圖

@foreach($recipes as $recipe)
<img class="recipeProfilePic" src="/storage/profile_pictures/{{What goes here}}" alt=""><a
        href="{{ route('user', $recipe->user_id) }}">
    <small>{{$recipe->author}}</small>
</a>
@endforeach

通過$ recipe,我可以訪問該特定配方的創建者的名稱,例如$recipe->author 我也試圖訪問此特定用戶的個人資料照片。 我想得到像這樣的$recipe->author->profile_pic (profile_pic是我的users表中的一列)。

我將如何以簡單的方式解決此問題? 我是編碼的新手,並且自己仍在努力解決這些問題。 謝謝!

您可以這樣做:

$recipe->user->profile_pic

您可以通過將user重命名為author來更改模型,如下所示:

public function author()
{
    return $this->belongsTo('App\User');
}

或像這樣更改視圖(刀片):

@foreach($recipes as $recipe)
<img class="recipeProfilePic" src="/storage/profile_pictures/{{What goes here}}" alt=""><a
        href="{{ route('user', $recipe->user_id) }}">
    <small>{{$recipe->user->profile_pic}}</small>
</a>
@endforeach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM