2
I’m developing an Intranet that will contemplate Categories and Posts. A post can receive "n" categories.
To that effect I’m using belongsToMany().
The problem is when returning this data with Post::find($idpost), it returns not only 1 record but all post records in that table pivot is related.
I haven’t found anything like it and I don’t know if I’m doing anything wrong.
The create is running perfectly, the problem is when I ask to return only 1 record.
I inserted belongsToMany() in the 2 tables, Posts and Categories.
Could someone tell me if this behavior is normal or if there is something wrong in 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');
}
}
I think I should return a record, only the post with id X
– Miguel
That’s right, Miguel. I have 3 Posts records, id 35, 36 and 39. Anyone who tests, he returns me all Posts. Not only the ID I want.
– Marco Garcia
Check on the model
Post
if you are acting at the right table,protected $table = ..
– Miguel
If you pass one
array
forfind
, it will bring more than one value. See if$idPost
is aarray
orint
.– Wallace Maxters
I used convention. Do I need to declare anyway? Table names are: posts and Categories
– Marco Garcia
the $idPost is integer... even tested by typing the numeric value, without variable.
– Marco Garcia
try to put the name of the pivot table as
category_post
in the singular...– RFL
@Marcogarcia enter the code of the 2 models, please.
– RFL
Ready @Rafaelacioly
– Marco Garcia