简体   繁体   中英

Laravel 5.8 Eloquent querying

I know all the Eloquent model querying is in the Laravel documentation and I have read through them to figure this out but can't seem to work my way around it. I am building a recipe application, and I want to get access to a particular profile picture of a user based on an uploaded recipe.

I have a grid of recipes that have been uploaded by various users. The User and Recipe model are below.

User Model

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

Recipe Model

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

In my recipe grid, I have the following code in a recipe card.

Index Blade/View

@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

Through the $recipe I can access the name of the creator of that particular recipe like this $recipe->author . I am trying to get access to this specific users profile photo too. I want to get something like this $recipe->author->profile_pic . (profile_pic is a column in my users table).

How would I go about solving this problem in a simple way? I'm a newcomer to coding and am still working on solving these problems myself. Thank you!

您可以这样做:

$recipe->user->profile_pic

You can change the model by rename user to author like this:

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

or changing view (blade) like this:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM