我有2个相关的表,我需要按月过滤表的日期
我的第一个表格包含以下字段:Id_agendamien_persona,Id_agendamiento,id_persona
第二个表格包含以下字段:Id_agendamiento,fecha
所以我需要在第二个表中过滤fecha,
Mi控制器
public function listar(){
$contactos = Contacto::pluck('completo','id_contacto');
$contacto_x_agendamientos = Contacto_x_Agendamiento::all();
array_add($contactos,0,"::Seleccione::");
return view('agendamiento.listar')->with(compact('contacto_x_agendamientos','contactos'));
}
我的模特
第一张表
class Contacto_x_Agendamiento extends Model
{
protected $table = "contacto_x_agendamiento";
protected $primaryKey = 'id_contacto_x_agendamiento';
const CREATED_AT = 'fecha_creado';
const UPDATED_AT = 'fecha_modificado';
public function Agendamiento(){
return $this->hasOne(Agendamiento::class,'id_agendamiento','id_agendamiento');
}
}
第二张表
class Agendamiento extends Model
{
protected $table = "agendamiento";
protected $primaryKey = 'id_agendamiento';
const CREATED_AT = 'fecha_creado';
const UPDATED_AT = 'fecha_modificado';
public function scopeMes($query){
return $query->whereMonth('fecha_agendar','=',date('m'))->get();
}
}
查看
<td>{{$contacto_x_agendamiento->Agendamiento->Mes()->fecha_agendar}}</td>
错误
此集合实例上不存在属性[fecha_agendar]。
答案 0 :(得分:0)
此处的问题是,您尝试从Agendamiento
中获取Collection
模型的属性,结果是您回来了。
这里有两个选择。您只使用->first()
:
echo $contacto_x_agendamiento->Agendamiento->Mes()->first()->fecha_agendar;
或者您迭代Collection
并打印每个fecha_agendar
属性:
foreach ($contacto_x_agendamiento->Agendamiento->Mes()->get() as $agendamiento) {
echo $agendamiento->fecha_agendar;
}
在旁注中,您应该完全重新考虑您的编码风格/惯例。我完全清楚它有效,但将id_contacto_x_agendamiento
作为主要ID或类名Contacto_x_Agendamiento
并非最佳做法。
还可以避免在课程/属性/变量中混合使用英语和西班牙语,以提高其他人的可读性。