【发布时间】:2020-02-23 06:41:24
【问题描述】:
我的网站上有一个用户最喜欢的列表,他们可以将他们最喜欢的房子添加到愿望列表中
一切顺利,但他看不到愿望清单页面,错误如下:
试图获取非对象的属性“图像”
这是我的关系
class Home extends Model
{
protected $guarded = [];
public function favorite()
{
return $this->hasMany(favorite::class,'house_id');
}
}
class favorite extends Model
{
protected $guarded = [];
public function house()
{
return $this->belongsTo(home::class);
}
}
我在控制器中的索引函数:
public function index()
{
$favorite = favorite::where('user_id',auth()->user()->id)->get();
return view('favorite.index',compact('favorite'));
}
我的索引:
@foreach($favorite as $fav)
<tr>
<td>
<a href="property-detail.html"><img src="{{$fav->home->image}}" alt=""
width="100"></a>
</td>
<td><a href="property-detail.html">{{$fav->home->title}}</a></td>
<td>خانه خانواده</td>
<td>اجاره</td>
<td>
<div class="price"><span>{{number_format($fav->home->price)}}</span><strong>تومان</strong>
</div>
</td>
<td>
<a href="#" class="action-button"><i class="fa fa-ban"></i> <span>حذف</span></a>
</td>
</tr>
@endforeach
【问题讨论】:
-
您的所有用户都有这个问题,还是只有 1 个?因为如果只有 1 个用户有这个问题,你需要验证 db 中与该用户收藏相关的所有数据是否正确。如果每个用户都有这个问题,那么您需要测试关系。如果是后者,您可以使用
php artisan tinker并使用App\favorite::whereUserId($someID)->first()->house()->get()之类的代码,其中$someID是用户ID。目标是看看你是否得到了有效的结果。
标签: php laravel laravel-5 relational-database relationship