【问题标题】:how can i fix "Trying to get property of non-object"我该如何解决“试图获取非对象的属性”
【发布时间】: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)-&gt;first()-&gt;house()-&gt;get() 之类的代码,其中$someID 是用户ID。目标是看看你是否得到了有效的结果。

标签: php laravel laravel-5 relational-database relationship


【解决方案1】:

您正在尝试访问名称错误的关系。你定义了名字house的关系:

public function house(){

    return $this->belongsTo(home::class);
}

所以你需要使用这个名字来访问:

@foreach($favorite as $fav)
    <tr>
        <td>
            <a href="property-detail.html"><img src="{{$fav->house->image}}" alt="" width="100"></a>
        </td>
        <td><a href="property-detail.html">{{$fav->house->title}}</a></td>
        <td>خانه خانواده</td>
        <td>اجاره</td>
        <td>
            <div class="price"><span>{{number_format($fav->house->price)}}</span><strong>تومان</strong>
            </div>
        </td>
        <td>
            <a href="#" class="action-button"><i class="fa fa-ban"></i> <span>حذف</span></a>
        </td>
    </tr>
@endforeach

但是如果house 关系为空,您也会遇到问题。为避免您可以使用@Mohammed Aktaa 提出的解决方案:

optional($fav->house)->title

【讨论】:

    【解决方案2】:

    首先你最喜欢的模型没有家庭关系,你的关系就是房子,当你想获得它的价值时,你可以使用optional这样的辅助函数:

    optional($fav->house)->title
    

    【讨论】:

    • 而且您也没有向房屋添加数据以将其与最喜欢的模型相关联
    猜你喜欢
    • 2019-03-11
    • 2020-03-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2020-08-14
    • 1970-01-01
    相关资源
    最近更新 更多