【问题标题】:Laravel 4 eloquent query to combine data from single tableLaravel 4 雄辩的查询来组合来自单个表的数据
【发布时间】:2013-07-04 03:00:42
【问题描述】:

我正在尝试制作一个电视节目表,其中显示每个频道的当前和下一个即将播出的节目。 我想做这样的事情:

            <table class="table">
                <thead>
                    <tr>
                        <th></th>
                        <th>Now Playing</th>
                        <th>Next Upcoming Show</th>
                    </tr>
                </thead>
                <tbody>
                @foreach ($shows as $show)
                    <tr>
                    <td>
                        <strong>{{ $show->channel->name}}</strong></td>
                    <td><strong>{{ date('H:i', strtotime($show->now->start)) }}</strong>
                       {{ $show->now->title }}</td>
                    <td><strong>{{ date('H:i', strtotime($show->next->start)) }}</strong>
                       {{ $show->next->title }}</td>
                    </tr>
                @endforeach        
                </tbody>
            </table>

我现在正在播放的节目是这样的: $shows = Show::with('channel') ->where('start', 'where('end', '>', DB::raw('(NOW() + INTERVAL 15 SECOND)')) ->orderBy('start')->get();

我似乎无法在同一个查询中获得每个频道的下一个即将播出的节目。 如果我能为当前的节目做这样的事情会很酷:$show->now->start 和下一个节目:$show->next->start

有什么想法吗?

我的数据库:

    Schema::create('channels', function(Blueprint $table) {     
         $table->increments('id');
         $table->string('name', 200);
         $table->timestamps();
    });

    Schema::create('shows', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('channel_id');
        $table->string('title', 255);
        $table->text('description')->nullable();
        $table->dateTime('start');
        $table->dateTime('end');
    });

【问题讨论】:

  • 有关您的数据库结构的更多信息,甚至是您尝试生成的原始查询,肯定会有所帮助。

标签: laravel laravel-4 eloquent


【解决方案1】:

也许反过来做会更容易?按频道循环并执行$channel-&gt;next-&gt;...$channel-&gt;now-&gt;...

在您的 Channel 模型中,您可以执行以下操作:

public function next()
{
    // Change this for your "get next" query
    return $this->hasOne('Show')->where('start', '<=', DB::raw('(NOW() - INTERVAL 15 SECOND)')) ->where('end', '>', DB::raw('(NOW() + INTERVAL 15 SECOND)')) ->orderBy('start');
}

public function now()
{
    return $this->hasOne('Show')->where('start', '<=', DB::raw('(NOW() - INTERVAL 15 SECOND)')) ->where('end', '>', DB::raw('(NOW() + INTERVAL 15 SECOND)')) ->orderBy('start');
}

然后做:

$channels = Channel::with(array('next', 'now'))->get();

@foreach($channels as $channel)
    Now: {{ $channel->now->title }} <br>
    Next: {{ $channel->next->title }}
@endforeach

我根本没有对此进行测试,这只是一个想法/建议。

【讨论】:

  • 哇杰斯帕!这就像一个魅力!不知道你可以在模型中做到这一点!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 2015-08-09
  • 2020-11-03
相关资源
最近更新 更多