【问题标题】:problem with relations, does not find properties关系有问题,找不到属性
【发布时间】:2021-09-16 13:35:07
【问题描述】:

我的关系有问题,没有找到属性,

错误:试图获取非对象的属性“服务”

控制器:

 public function index(Request $personal){


    $personal = Personal::where('nombre' , $personal)->with('nombre')->get();
    $servicios = \App\Models\Eventos::orderByDesc('hora')->get();



    return view('personal', compact('servicios','personal'));

   
  }

模型服务:

    class Servicios extends Model
{
    use HasFactory;

    public function eventos()
    {
        return $this->belongsTo(Evento::class);
    }

    public function personal()
    {
        return $this->belongsTo(Personal::class);
    }
}

模型事件:

 class Eventos extends Model
{
    protected $table= 'eventos';

    //
    protected $fillable = [
        'titulo', 'descripcion', 'fecha', 'hora', 'prioridad', 'servicio', 'personal',
    ];

    public $timestamps = false;

    public function servicio()
    {
        return $this->belongsTo(Servicios::class);
    }
    public function personal()
    {
        return $this->belongsTo(Personal::class);
    }

在blade.php中:

@foreach ($servicios as $hoy)
  <td>{{$hoy->servicio_id->servicio}}</td>
  @endforeach

数据库:

https://i.imgur.com/LvjR6qS.png

我不明白错误所以我没有找到该属性

【问题讨论】:

  • $hoy-&gt;servicio_id 返回 1 或 2(integer),而 1-&gt;servico2-&gt;servico 不是有效代码...您的意思是 $hoy-&gt;servico-&gt;servico? (由于使用不同的语言,表、列和关系名称有点难以理解)
  • 是的,$hoy->servicio_id 返回 1 或 2。但是 $hoy->servico->servicio 返回错误
  • 您尝试做的事情无效且令人困惑。 servico_id 是整数而不是模型。
  • 是的,它是一个整数,它是事件表与服务表相关的数字

标签: php laravel laravel-5 eloquent laravel-8


【解决方案1】:

Laravel 中,您可以访问作为属性访问的函数名称的关系。

以下内容应该可以解决您的问题。有关系fillable 什么都不做。

@foreach ($servicios as $hoy)
    <td>{{ $hoy->servicio->servicio_property_to_access }}</td>
@endforeach

更新

如果我没记错的话,你的模型上有一个 servicio 字段,重命名关系可能会有所帮助。

class Eventos extends Model
{
    public function servicioRelationship()
    {
        return $this->belongsTo(Servicios::class);
    }

@foreach ($servicios as $hoy)
    <td>{{ $hoy->servicioRelationship->servicio }}</td>
@endforeach

【讨论】:

  • i.imgur.com/yKv8ybV.png 打印错误,很混乱
  • servicio_property_to_access 是一个通用属性,您应该将其替换为您要访问的属性。 servicio 是你的模型,所以无论你想访问它:)
  • 能否请您附上您要打印的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 2020-01-21
相关资源
最近更新 更多