Laravel 5.8雄辩的查询

我知道所有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,我可以访问该特定配方的创建者的名称,例如this $recipe->author。我也试图访问此特定用户的个人资料照片。我想得到这样的东西$recipe->author->profile_pic。(profile_pic是我的用户表中的一列)。


我将如何以一种简单的方式解决这个问题?我是编码的新手,我仍在自己解决这些问题。谢谢!


蝴蝶不菲
浏览 147回答 2
2回答

慕斯王

您可以这样做:$recipe->user->profile_pic

拉莫斯之舞

您可以通过重命名user来更改模型,author如下所示:public function author(){&nbsp; &nbsp; return $this->belongsTo('App\User');}或像这样更改视图(刀片):@foreach($recipes as $recipe)<img class="recipeProfilePic" src="/storage/profile_pictures/{{What goes here}}" alt=""><a&nbsp; &nbsp; &nbsp; &nbsp; href="{{ route('user', $recipe->user_id) }}">&nbsp; &nbsp; <small>{{$recipe->user->profile_pic}}</small></a>@endforeach
打开App,查看更多内容
随时随地看视频慕课网APP