通过数据透视表传递数据?

时间:2018-06-03 12:28:02

标签: php laravel-5

我有三个表,即活动,类别和activity_categories表。每个活动可能属于许多类别,因此category_id和activity_id保存在activity_categories中。 我试图每个产品只获得一个类别,因为要显示每个活动使用一个类别图像,但在搜索时我必须在所有所有类别中显示它们。我创建了我的模型如下:

    class Activity extends Model
{
    protected $table = "activities";

    public function category()
    {
        return $this->belongsToMany('App\Category','activity_categories');
    }

}

//控制器

public function userActivities()
{
    $user_id = Auth::user()->id;
    $activities = Activity::all()->where('user_id', $user_id);

    return view('user_profile.activities', compact( 'activities' ));
}

//视图

@foreach($activities as $activity)
                    <div class="col-lg-4 col-md-4 col-xs-12" id="profile-card">
                        <div class="widget-head-color-box navy-bg p-lg text-center"
                             style="background-image: url('{{asset('/images/categories/'.$activity->category->first()->image)}}')">
                            <img src="/storage/profile/{{Auth::user()->image}}" class="img-small-profile" alt="profile">
                            <button id="heart-favorite" class="btn btn-danger btn-circle btn-outline"
                                    type="button"><i
                                        class="fa fa-heart"></i></button>
                        </div>
                        <div class="widget-text-box">
                            <h3 class="media-heading m-t-md"><b>{{$activity->title}}</b></h3>
                            <h5 class="media-heading m-t-md" style="text-align: justify">
                                {{$activity->description}}<br><br>
                            </h5>
                        </div>
                    </div>
                @endforeach

当我使用dd($ activity-&gt; category-&gt; first() - &gt; image)时,它会显示数据,但是当我在视图中放置相同时,ID会显示错误“试图获取非属性对象“

0 个答案:

没有答案