Create Fake Relationship/Relationship in Laravel model

Asked

Viewed 70 times

1

I have a model for my post table, it looks like this:

$post = Post::where('titulo_url', $titulo_url)->first();
//$post->id
//$post->categoria_id
//$post->titulo_url
//$post->titulo
//$post->texto

As you might have imagined, categoria_id is a Relationship with another model/table, the 'categories'

class Post extends Model{
    public function categoria(){
        return $this->belongsTo('App\Categoria');
    }
}

Through the $post->categoria can return all category data such as $post->categoria->nome, for example...


I also have the need to have the return of a next post in my post, I got it doing this in the controller:

$post = Post::where('titulo_url', $titulo_url)->first();
$post->proximo = DB::table('posts')->where('id', '>', $retorno->id)->orderBy('id', 'asc')->first();

With that, I get through the $post, also have return from the next post... Like this:

$post->proximo->id;
$post->proximo->nome;

almost a simulation of kinship.

How to do directly inside the model this "Relationship" with the next post?

1 answer

1

Return an instance of DB is not the same as an instance of Post. It may look the same but it’s completely different.

Change your code to return an instance of Post:

$post = Post::where('titulo_url', $titulo_url)->first();
$proximoPost = Post::where('id', '>', $retorno->id)->orderBy('id', 'asc')->first();

You could also extract this logic from the next Post into the model:

class Post extends Model{
    public function categoria(){
        return $this->belongsTo('App\Categoria');
    }

    public function nextPost(){
        // Aqui vem a lógica para retornar uma nova instancia do Post seguinte
        return $this->where('id', '>', $this->id)->orderBy('id', 'asc')->first();
    }
}

In this case on your controller:

$post->nextPost()->categoria->nome;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.