douqiju2520
2018-12-03 16:04
浏览 74
已采纳

Laravel Eloquent:hasManyThrough还是其他什么?

In Laravel 5.7 I have read the Has Many Through documentation but I still can't use it correctly for my case.

Here's the DB:

Analytics

    id
    data
    subscriber_id

Subscribers

    id
    city_id

Cities

    id
    name

I need the Analytics model to get data from Analytics with subscribers.id and cities.name

What I have done:

Connected Analytics and Subscribers models

<?php

class Analytics extends Model
{
    public function subscriber()
    {
        return $this->belongsTo('App\Models\Subscriber');
    }
}

class Subscriber extends Model
{
    public function analytics()
    {
        return $this->hasMany('App\Models\Analytics');
    }
}

Made a request that gets the data from the Analytics table with subscribers data:

$results = Analytics::where('survey_id', '4')
    ->with('subscriber')
    ->whereDate('created_at', '>=', $last_survey_date)
    ->orderBy('data')
    ->get();

If anybody has any ideas how to get city names, please, share it.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题