【问题标题】:errorexception laravel recovery foreign keys错误异常 laravel 恢复外键
【发布时间】:2022-12-19 15:52:31
【问题描述】:

我有 3 个表,用户,Casas 和 Reservas,来自预订 index 我想得到相关的房子的名字,但我得到 以下错误:

Trying to get property 'nombre' of non-object (View: 
C:\laragon\www\casaRural\resources\views\reservas\index.blade.php)

并像这样检索值:

@forelse($reservas as $reserva)

    <tr>

      <th scope="row">{{ Auth::user()->name  }}</th>

      <td>{{$reserva->casas->nombre}}</td>

    </tr>

    @empty

    <h2>El usuario {{ Auth::user()->name  }} no tiene reservas en la casa -></h2>

    @endforelse

家庭关系

class Reservas extends Model
{
    use HasFactory;
    protected $fillable=['capacidad','fechaEntrada','fechaSalida'];
    protected static function boot(){   
        parent::boot();
        self:: creating(function($table){
            if(!app()->runningInConsole()){
            $table->user_id = auth()->id();
            $table->casa_id = casas()->id();
            }
        }
         );
        }

      public function user(){
        return $this->belongsTo(User::class);
    }
    public function casas(){
        return $this->belongsTo(Casas::class);
    }
}

珍藏

   public function user(){
        return $this->belongsTo(User::class);
    }
    public function reservas(){
        return $this->hasMany(Reservas::class);
    }

【问题讨论】:

  • 请提供足够的代码,以便其他人可以更好地理解或重现问题。

标签: php laravel relational-database


【解决方案1】:

BelongsTo 是单数

class Reservas extends Model
{
    use HasFactory;
    protected $fillable=['capacidad','fechaEntrada','fechaSalida'];
    protected static function boot(){   
        parent::boot();
        self:: creating(function($table){
            if(!app()->runningInConsole()){
            $table->user_id = auth()->id();
            $table->casa_id = casas()->id();
            }
        }
         );
        }

      public function user(){
        return $this->belongsTo(User::class);
    }
    public function casa(){
        return $this->belongsTo(Casas::class);
    }
}

【讨论】:

    猜你喜欢
    • 2016-03-22
    • 2011-03-03
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多