简体   繁体   English

Laravel上一个和下一个记录,返回对象

[英]Laravel previous and next records, return object

I'm trying to get the previous record from a database so I can link to it. 我正在尝试从数据库中获取以前的记录,以便可以链接到它。

The $previous_comic in this function just returns the published_at field and I can't do anything with that. 此函数中的$previous_comic仅返回published_at字段,对此我无能为力。

public function index()
{
    $newest_comic = Comic::orderBy('published_at', 'DESC')->first();

    $previous_comic = Comic::where('published_at', '<', $newest_comic->published_at)->max('published_at');

    return View::make('comics.index')->with('newest_comic', $newest_comic)->with('previous_comic', $previous_comic);
}

I need the object so I can use {{ $previous_comic->slug }} 我需要该对象,因此可以使用{{ $previous_comic->slug }}

Right now it just returns 现在就回来了

"Trying to get property of non-object." “试图获取非对象的属性。”

How could I do this? 我该怎么办?

Thanks! 谢谢!

$comics = Comic::orderBy('published_at', 'DESC')->take(2)->get();

$newest_comic = $comics[0];

$previous_comic = $comics[1];

I can think of 3 possible scenarios. 我可以想到3种可能的情况。 Maybe one of them will help you: 也许其中之一会帮助您:

1) Is your query returning an array of objects, in which case do you need to loop through them to access the property? 1)您的查询是否返回一个对象数组,在这种情况下,您需要遍历它们以访问属性吗?

2) Have you definitely created the 'slug' fields in your database? 2)您是否确实在数据库中创建了“ slug”字段?

3)Is $previous_comic definitely an object and not an array? 3)$ previous_comic肯定是对象而不是数组吗? IE should you be using $previous_comic['slug'] IE应该使用$ previous_comic ['slug']

I'm familiar with Laravel but not massively experienced and I suspect no. 我熟悉Laravel,但经验不足,我怀疑没有。 3 is not the cause of your problem. 3不是您的问题的原因。

Hopefully this helps. 希望这会有所帮助。 Feel free to give any extra details if you have them. 如果您有其他任何细节,请随时提供。

Lew. w

You should also think about the case when the current record is the first one 您还应该考虑当前记录是第一条记录的情况

    $comic = Comic::findOrFail($id);
    $comics = Comic::orderBy('id')->get();

    $current = $orgs->search($org);

    $prev = ($current == 0) ? $comics->count() - 1 : $current - 1;
    $prevComic = $orgs->get($prev);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM