belongsToMany Laravel - find ()

2

I'm developing an Intranet that will span Categories and Posts . A post can receive "n" categories.

For this purpose I am using belongsToMany () .

The problem is when returning this data with Post :: find ($ idpost) , it returns not only 1 record but all post records where the pivot table > is related.

I did not find anything like this and I do not know if I'm doing something wrong.

The create is running perfectly, the problem is when I ask to return only 1 record.

I have belongsToMany () in the 2 tables, Posts and Categories .

Can anyone tell me if this behavior is normal or if there is something wrong with the logic / construction?

PS: Laravel 5.2

EDIT

Post
table: posts
pk: id

Category
table: categories
pk: id

Pivot
table: category_post
pk: id
fk: post_id
fk: category_id

namespace App\Intranet;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $connection = 'mysql_intranet';
    protected $fillable = ['title', 'text', 'categories'];

    public function categories()
    {
        return $this->belongsToMany('App\Intranet\Category');
    }
}



namespace App\Intranet;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $connection = 'mysql_intranet';
    protected $fillable = ['categoria', 'herdado'];

    public function posts()
    {
        return $this->belongsToMany('App\Intranet\Post');
    }
}
    
asked by anonymous 19.08.2016 / 13:41

3 answers

1

You can use hasMany instead of belongsToMany . It would be belongsToMany if you made SELECT through the CategoryPost table.

Model

Post.php

public function categorias(){
    return $this->hasMany('App\CategoryPost', 'post_id');
}

Controller

MainController.php

use App\Post;    
public function index(){

    $posts = Post::find(1);    
    dd($posts->categorias);
}
    
19.08.2016 / 15:58
1

Have you tried using the hasManyThrough relationship? It serves exactly for ManyToMany relationship, which is what seems to be your case.

You have a complete example in the Laravel documentation in this Link below:

link

Using hasManyThrough , you can define the relationship in both Models and access the multiple related records of each.

I hope I have helped! ;)

    
26.08.2016 / 18:21
0

The convention for pivots is the name of each table (singular) separated by _ in alphabetical order.

category_post

    
19.08.2016 / 15:19