Create fake relationship in model Laravel

1

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

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

As you may have guessed, category_id is a Relationship with another model / table, the 'categories'

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

By $post->categoria I can return all data in the category, 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 this by 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 this, I get through $post , also have next post return ... So:

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

Almost a simulation of kinship.

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

    
asked by anonymous 21.10.2015 / 03:36

1 answer

1

Returning an instance of DB is not the same thing as an instance of Post . It may look the same but it's completely different things.

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;
    
21.10.2015 / 04:37