lundi 23 juillet 2018

Eloquent Relations: how to order topics by newest posts?

I created a table like this (table name: supports):

$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

$table->integer('parent_id')->unsigned()->nullable();
$table->foreign('parent_id')->references('id')->on('supports')->onDelete('cascade');

$table->text('body');

in support model I do this:

public function supports()
{
    return $this->hasMany(Support::class , 'parent_id' , 'id');
}

public function latestSupport()
{
    return $this->hasOne(Support::class,'parent_id','id')->orderBy('created_at', 'desc')->latest();
}

And Finally I try call this function (in model) in controller:

public function scopeSearch($query, $input, $pagination)
{
    $query->where('parent_id',null);
    $query->with('latestSupport');

    return $query->latest()->paginate($pagination);
 }

It return list of root (topics) ...But It couldn't sort roots by newest post for each root.

Could you please tell me the wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire