【问题标题】:Laravel inverse one to many relationshipLaravel 逆一对多关系
【发布时间】:2020-10-23 20:18:23
【问题描述】:

我正在尝试连接两个模型,其中模型 Event 由 Event 内部字段“agenda_id”上的 Agenda 所有,但是当我尝试使用 ->with('agenda') 调用关系时,我使用 DB::getQueryLog() 得到以下查询:

"select * from agendas where 0 = 1"

我的事件模型:

class Event extends Model
{
    protected $fillable = [
        'agenda_id',
        'title',
        'start_date',
        'start_time',
        'end_date',
        'end_time',
        'all_day',
        'description',
        'created_by',
        'tenant_id'
    ];

    public function agenda()
    {
        return $this->belongsTo(Agenda::class, 'agenda_id');
    }
}

我的议程模型:

class Agenda extends Model
{
    protected $fillable = [
        'name',
        'icon',
        'created_by',
        'tenant_id'
    ];

    public function events()
    {
        return $this->hasMany(Event::class);
    }
}

我正在尝试使用的雄辩的查询:

$events = Event::with('agenda')->get(['id', 'title', 'start_date', 'start_time', 'end_date', 'end_time']);

这些表的外观示例:

活动:

议程:

【问题讨论】:

  • 如果我对您的理解正确,您是在尝试将活动与家长议程联系起来。我认为 with() 函数通过引入子实体来工作。一探究竟。首先,如果你不介意议程加载了一个惰性调用 $ this-> belongsTo (Agenda :: class, 'agenda_id'),则不需要使用 with() 函数
  • 你指的“$this”是什么?
  • 你可以试试 $events = Event::with('agenda')->get();
  • @Roman 对不起,我已经用 Event:: 替换了该行
  • @Abdulmajeed 仍然无法正常工作。

标签: laravel eloquent


【解决方案1】:

事实证明,您需要在 eloquent 查询的 get([]) 部分调用关系的 id 才能使关系起作用。

有效的代码:

$events = Event::where('tenant_id', $tenant_id)->whereIn('agenda_id', $agenda_id)->whereBetween('start_date', [$start_date, $end_date])->with('agenda')->get(['id', 'title', 'start_date', 'start_time', 'end_date', 'end_time', 'agenda_id']);

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 2017-07-16
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2018-09-27
    • 2017-12-24
    相关资源
    最近更新 更多