Php Laravel 8:试图获得财产';名称';多对多关系中的非对象

Php Laravel 8:试图获得财产';名称';多对多关系中的非对象,php,laravel,laravel-8,Php,Laravel,Laravel 8,我正在与Laravel 8合作开发我的项目,在这个项目中,我有一个名为hostings的表,其中包含一些主机名的列表和另一个名为details的表,它基本上是关于每个主机的一些信息 下面是Hosting.php模型: protected $fillable = ['name']; public function details() { return $this->belongsToMany(Detail::class); } protected $fil

我正在与Laravel 8合作开发我的项目,在这个项目中,我有一个名为
hostings
的表,其中包含一些主机名的列表和另一个名为
details
的表,它基本上是关于每个主机的一些信息

下面是
Hosting.php
模型:

protected $fillable = ['name'];

public function details()
    {
        return $this->belongsToMany(Detail::class);
    }
protected $fillable = ['name'];

public function details()
    {
        return $this->belongsToMany('Hosting');
    }
下面是
Detail.php
模型:

protected $fillable = ['name'];

public function details()
    {
        return $this->belongsToMany(Detail::class);
    }
protected $fillable = ['name'];

public function details()
    {
        return $this->belongsToMany('Hosting');
    }
然后,
details
table和
detail\u hosting
table的迁移如下:

public function up()
    {
        Schema::create('details', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('detail_hosting', function (Blueprint $table) {
            $table->bigInteger('hosting_id')->unsigned()->index();
            $table->bigInteger('detail_id')->unsigned()->index();
            $table->foreign('hosting_id')->references('id')->on('hostings')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('detail_id')->references('id')->on('details')->onDelete('cascade')->onUpdate('cascade');
        });
    }
现在我想展示每个托管服务的详细信息,因此在刀片服务器上,我添加了:

 @foreach($all as $one)
    <div class="packages">
        <div class="pricing-title">
            {{ $one->name }}
        </div>{
        <h2 class="text1">{{ $one->details->first()->name }}</h2>
        <a href="#" class="button pricing-button">Start Now</a>
    </div>
@endforeach
但现在的问题是,我得到了这个错误,并正确地显示了每个主机的详细信息:

ErrorException尝试获取非对象的属性“name”


那么如何修复此错误呢?

您可以使用下面的方法来处理错误,并在没有任何详细信息的情况下进行调试:

{{ $one->details->first() && $one->details->first()->name }}

这里您并没有遵循Laravel命名约定,所以您必须像这样定义关系表和外键名称

 $this->belongsToMany(Detail::class, 'detail_hosting', 'hosting_id', 'detail_id');
更多信息