I have a Sites
model which hasMany Posts
.
I would like to know whats the most efficient eloquent query to return all Site records along with the 1 (most recent) Post record.
I have tried using this in my Sites modal but it returns all Posts which is not what I want.
public function lastPost()
{
return $this->hasMany('App\Post')->last();
}
Another issue I am having is trying to print a single column in my view. {{ $site->lastPack->name }}
returns
$name undefined property
... despite this being a valid column in my Post model.
Change Your lastPost
relationship to hasOne
like so:
public function lastPost()
{
return $this->hasOne('App\Post')->latest('id');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.