Laravel 5.4 belongsToMany relationship returns empty - laravel

In Laravel 5.4 I'am trying to set up a Many To Many Relation. but the belongsToMany returns empty! Here's my migrations and models.
botusers Table:
public function up()
{
Schema::create('botusers', function (Blueprint $table) {
$table->increments('id');
$table->integer('t_id');
$table->string('first_name');
$table->string('last_name');
$table->string('username');
$table->string('mobile');
$table->timestamps();
});
}
candidates Table:
public function up()
{
Schema::create('candidates', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('token');
$table->string('degree');
$table->integer('age');
$table->text('desc');
$table->string('photo_url');
$table->string('cv_url');
$table->timestamps();
});
}
Third table, botuser_candidate Table:
public function up()
{
Schema::create('botuser_candidate', function (Blueprint $table) {
$table->integer('botuser_id');
$table->integer('candidate_id');
});
}
and the votes() method in Botuser Model:
public function votes()
{
return $this->belongsToMany(Candidate::class)->get();
}
When I fire the votes() method returns an empty array. and I also tested bellow method too,
public function votes()
{
return $this->belongsToMany(Candidate::class,'botuser_candidate','botuser_id','candidate_id')->get();
}
What I missed here? What should I do?
Edit:
I also added the foreign keys to the relation but the result is still same!

I would suggest you remove the get() method on the belongsToMany
Then query the database with
$c=new App\Candidate;
$c->with('votes')->get()
if you still want to use $c->votes() then you would have to do some changes to your functions. Lets use scope to achieve it.
public function candidates()
{
return $this->belongsToMany(Candidate::class,'botuser_candidate','botuser_id','candidate_id');
}
public function scopeVotes($query)
{
return $query->with("candidates")->get();
}
Then now we can call $v->votes() and it should return all your record.
Calling get() directly on belongsToMany method will return empty array.

Related

BadMethodCallException: Trying to list all partners with the categories laravel

I'm experiencing the following:
Goal: I would like to list all partners and the categories they belong to. Basically, it's a many to many relationship.
Below is the code:
Partner Categories Table Migration
public function up()
{
Schema::create('partcats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('partcatnameP')->unique();
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Partners Table Migration
public function up()
{
Schema::create('partners', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('partnername');
$table->string('regnumber')->unique();
$table->unsignedBigInteger('activestatus_id')->unsigned();
$table->foreign('activestatus_id')->references('id')->on('activestatuses');
$table->unsignedBigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Partner_Category Migration
public function up()
{
Schema::create('partner_partcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('partner_id')->unsigned();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
$table->unsignedBigInteger('partcat_id')->unsigned();
$table->foreign('partcat_id')->references('id')->on('partcats')->onDelete('cascade');
$table->timestamps();
});
}
Models are as shown below:
Partcat Model
public function partners()
{
return $this->belongsToMany('App\Partcat','partner_partcat');
}
Partner Model
public function partcats()
{
return $this->belongsToMany('App\Partcat','partner_partcat');
}
and the Partners Controller is as shown below:
public function index()
{
//
$partners = Partner::all()->partcats();
// dd(Partner::all()->partcats());
return view('partners.index',['partners'=>$partners]);
}
This is where I'm trying to retrieve the list of partners and its related categories. However, I get a BadMethod call error.
You can use the following method
$partners = Partner::with('partcats')->get();
https://laravel.com/docs/5.6/eloquent-relationships#eager-loading
A many to many pivot table typically has the id for both tables it is relating.
The Partner_Category migration you have posted only seems to contain a partner_id. You may need to add in the category_id.
public function up()
{
Schema::create('partner_partcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('partner_id')->unsigned();
$table->unsignedBigInteger('partcat_id')->unsigned();
$table->timestamps();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
$table->foreign('partcat_id')->references('id')->on('partcats')->onDelete('cascade');
});
}

Fetching Relationship Model Data

I have the Below Table Structure
Users table
id- integer
name-string
Casefiles table
id- integer
user_id- foreign_key
name-string
Followups table
id- integer
date- date
casefile_id-foreign_key
I'm using the below Relationship between this models
User.php
public function casefiles()
{
if ($this->hasRole(['sales_executive'])) {
return Casefile::where('user_id', $this->id);
}
}
Casefile.php
public function user()
{
return $this->belongsTo('App\User');
}
public function followups()
{
return $this->hasMany('App\FollowUp');
}
Followup.php
public function casefile()
{
return $this->belongsTo('App\Casefile');
}
I want to fetch Users followups directly. How can i achive this ?
you need to use hasManyThrough() in your User.php you can add this,
public function followUps()
{
return $this->hasManyThrough('App\FollowUp','App\Casefile');
}
then you can normally call the followups using User::with('followUps')->find(1)->followUps
I have noticed that you are checking role in your relationship $this->hasRole(['sales_executive'] this may occur error as you are not if the statement is false. I think you take another approached and handle that as well. for more information on hasManyThrough prefer this link
This should be the case for a HasManyThrough Relationship.
In your case it should be
// Followups migration
Schema::create('followups', function (Blueprint $table) {
$table->bigIncrements('id');
$table->date('date');
$table->unsignedBigInteger('casefile_id')->nullable();
$table->timestamps();
$table->foreign('casefile_id')
->references('id')
->on('casefiles');
});
// Casefile migration
Schema::create('casefiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users');
});
// User.php
public function followups() {
return $this->hasManyThrough(FollowUp::class, Casefile::class);
}
// YourController.php
$user = User::all()->first();
dd($user->followups);

accessing nested relationship in laravel 5

i have 3 models like below :
Date
Property
PropertyDetail
and here is my migration for tables i write in order
Date :
public function up()
{
Schema::create('dates', function (Blueprint $table) {
$table->bigIncrements('id');
$table->dateTime('date');
$table->timestamps();
});
}
Property :
public function up()
{
Schema::create('properties', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('type');
$table->text('title');
$table->integer('base_capacity');
$table->timestamps();
});
and PropertyDetail :
public function up()
{
Schema::create('property_details', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('property_id');
$table->string('state');
$table->string('city');
$table->timestamps();
});
}
i tried to remove unnecessarily fields from migration so to keep it clean so here is my 2 relations bettwen date and proeprties
Datemodel :
public function properties() {
return $this->belongsToMany(Property::class);
}
and propery model :
public function dates(){
return $this->belongsToMany(Date::class);
}
public function features(){
return $this->hasMany(Feature::class);
}
ok now finally in my controller i want to do this :
$search = Date::with('properties')
->where('date',$someday)->get()
->and some how here i want to select the city from the property detail table
;
so here is my problem , now i can easily access properties and show thier name but from this relation how can i access features relation and select the city from there should i use joins or some thing there i hope i was clear enough that what i want to do
You can do this:
Property model:
public function details(){
return $this->belongsToMany(Details::class,'property_details','id','property_id');
}
and in Date model:
public function properties() {
return $this->belongsToMany(Property::class);
}
public function propertiesDetails() {
return $this->properties()->with('details');
}
and in your controller you can get detail of properties by use:
$search = Date::with('propertiesDetails')
->where('date',$someday)->get();
now you can access to details of properties.
Hope it helps.

Laravel, pivot table conflicts with many-to-many relationship

Hey guys so I'm using spatie binary uuid package and I had few doubts
Things done so far:
User.php Migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->uuid('uuid');
$table->primary('uuid');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Role migration just have basic field called "name" with timestamps
Pivot table: role_user
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned()->nullable()->index();
$table->uuid('user_uuid');
});
}
I know this is terribly wrong and I don't know what to do, I'm trying to save the Role model via this call
$uuid = '478d7068-ae64-11e8-a665-2c600cf6267b';
$model = User::withUuid($uuid)->first();
$model->roles()->save(new Role(['name' => 'Admin']));
it doesn't work, where am I going wrong? I think it has something to do with role_user migration
User.php
public function roles()
{
return $this->belongsToMany(Role::class);
}
try this, pivot migration:
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned()->nullable()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->uuid('user_uuid');
$table->foreign('user_uuid')->references('uuid')->on('users')->onDelete('cascade');
});
}
roles relation:
public function roles(){
return $this->belongsToMany(Role::class,'role_user','user_uuid','role_id');
}
please let me know if it didn't work
you should edit your relation to this
return $this->belongsToMany(Role::class,'role_user','user_uuid','role_id');
if you say about your error we better can help you

How to make relationship without using modelname_id in laravel?

I am trying to use one to many relationship for post and category.And for the database columns,If i use like this
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('category_id');
$table->timestamps();
});
in Post model
public function Category()
{
return $this->belongsTo('App\Category');
}
in category model
public function posts()
{
return $this->hasMany('App\Post');
}
Its working if i use above method like $table->integer('category_id').But i want to use custom name like
$table->integer('cat_id') without using category_id like
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('cat_id');
$table->timestamps();
});
.I am using laravel 5.4 and please help me out. Thanks.
If you check out Laravel's site on Eloquent: Relationships under One To Many relationships, you'll see:
Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method:
return $this->hasMany('App\Comment', 'foreign_key');
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
This is also the case for $this->belongsTo which is just an inverse One To Many relationship. So in your case:
return $this->belongsTo('App\Category', 'cat_id');

Resources