im having a error with my app, it looks averything fine, but is creating a wrong query, but i have my tables and models right, basically i have a registration of a user that can select more than one regions and industry/area. My error is:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'hjobs.region_user' doesn't exist (SQL: select `region_id` from `region_user` where `user_id` is null)
Model User:
public function regionsToWork(){
return $this->belongsToMany(Region::class);
}
public function industriesToWork(){
return $this->belongsToMany(Industry::class);
}
AuthController:
$user = new User();
$user->name = $data['name'];
...
$user->regionsToWork()->sync($data['region'], false);
$user->industriesToWork()->sync($data['industry'], false);
$user->save();
Tables DB: USER:
-id;
-email
...
user_industry:
id;
user_id;
industry_id;
user_region:
id;
user_id;
region_id;
Migrations user_region_table_creation
Schema::create('user_region', function($table){
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('region_id')->unsigned();
$table->foreign('region_id')->references('id')->on('regions');
});
user_industry_table_creation
Schema::create('user_industry', function($table){
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('industry_id')->unsigned();
$table->foreign('industry_id')->references('id')->on('industries');
});
It looks like the pivot table name is different than what it's expecting, region_user as opposed to user_region.
You can manually specify the pivot table name in your belongsToMany method like this:
return $this->belongsToMany(Region::class, 'user_region');
Related
Hello I am working on a project, that in this part, to get a dependent dropdown i want to get all the «Areas de Interesse» that are attached to a specific user, getting this, by his ID, that is in the pivot table.
These are my migrations:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->string('profile_photo_path', 2048)->nullable();
$table->timestamps();
});
Schema::create('area_interesse', function (Blueprint $table) {
$table->id();
$table->string('area_interesse');
$table->string('area_interesse_ing');
$table->timestamps();
});
Schema::create('utilizador_interesse', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger("id_utilizador");
$table->foreign('id_utilizador')->references('id')->on('users')->onDelete('cascade');;
$table->unsignedBigInteger("id_interesse");
$table->foreign('id_interesse')->references('id')->on('area_interesse');
$table->timestamps();
});
And my models:
class AreaInteresse extends Model
{
protected $table = "area_interesse";
public function users(){
return $this->belongsToMany(User::class, 'utilizador_interesse', 'id_interesse' , 'id_utilizador');
}
}
class User extends Authenticatable
{
public function interesses(){
return $this->belongsToMany(AreaInteresse::class, 'utilizador_interesse', 'id_utilizador', 'id_interesse');
}
}
In my controller i tried to do this, base on every example i saw, has for testing, i am trying to get all «Areas de Interesse» that are related to the user with id 11
$interesses = AreaInteresse::with('users')
->whereHas('users', function($q){
$q->wherePivot('id_utilizador', 11);
})
->get();
However i am getting this error and i have no idea why it's happening, and why it is assuming i am trying to call a column «pivot»
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pivot' in 'where clause' (SQL: select * from `area_interesse` where exists (select * from `users` inner join `utilizador_interesse` on `users`.`id` = `utilizador_interesse`.`id_utilizador` where `area_interesse`.`id` = `utilizador_interesse`.`id_interesse` and `pivot` = id_utilizador))
"I am trying to get all «Areas de Interesse» that are related to the user with id 11"
This is exactly why relationships are defined between models. Just instantiate the user and then get the related models:
$user = User::findOrFail(11);
$interesses = $user->interesses;
As mentioned in comments, and worth repeating here, you should call your class Utilizadore instead of User, or change table and column names to match the name of the class.
I am new to Laravel and Eloquent is quite a challenge for me to understand. I have a User and a UserProfile model and table. UserProfile table has user_id (FK to user's id), 'key, and value fields.
I want to get the values of all the UserProfile fields associated with the user_id. Here is my code but nothing works. I am sure I am making some stupid mistakes but still learning :) Laravel.
UserProfile Model
class UserProfile extends Model
{
public $timestamps = FALSE;
protected $fillable = [
'user_id',
'key',
'value',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
User Model method
public function profileFields(){
return $this->hasMany(UserProfile::class);
}
UserProfile Migration
public function up()
{
Schema::create('user_profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->string('key', 191);
$table->longText('value');
$table->foreign('user_id', 'user_profile_uid_fk')
->references('id')
->on('users')
->onDelete('cascade');
$table->unique(['user_id', 'key'], 'user_profile_unique_key');
});
}
I am trying to get the profile fields for the user using User::findOrFail(10)->profileFields but it is giving me property not defined exception.
Need Help: Can anyone help me to make it work so I can get all user_profiles
fields from the profile table?
Error Output (Tinker)
>>> User::findOrFail(10)->profileFields
Illuminate/Database/QueryException with message 'SQLSTATE[42S02]: Base
table or view not found: 1146 Table 'velvetpaper.user_user_profile'
doesn't exist (SQL: select user_profiles.*,
user_user_profile.user_id as pivot_user_id,
user_user_profile.user_profile_id as pivot_user_profile_id from
user_profiles inner join user_user_profile on user_profiles.id
= user_user_profile.user_profile_id where user_user_profile.user_id = 10)'
The relation between users and user_profiles is a one to many.
You might have not restarted Tinker since you are getting the wrong error, dont forget to exit Tinker after the modification in the code. Once tinker is started, code changes wont affect it.
you can use join to implement this stuff. like this...
this is query builder
$data['profile']=DB::table(usertable)
->where('usertable.id',$id)
->leftjoin('userprofiletable','usertable.id','=','userprofiletable.user_id')
->first();
return view('profile_view',$data)
//view
$profile->fullname
$profile->sex
$profile->phone
...
I'm trying to get the results using laravel many to many relationship but the query is generating wrong therefore it return empty array.
$user->survey()->get() is returning empty array.
$user->survey()->toSql() is returning wrong query:
SELECT
*
FROM
`survey`
INNER JOIN `survey_user` ON `survey`.`id` = `survey_user`.`survey_id`
WHERE
`survey_user`.`user_id` IS NULL
Here, in the end, the user_id should not be null.
Migration for the survey pivot table:
Schema::create('survey_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('survey_id')->unsigned();
$table->string('status', 50)->nullable();
$table->timestamps();
});
Schema::table('survey_user', function (Blueprint $table) {
$table->foreign('user_id')->on('users')->references('id');
$table->foreign('survey_id')->references('id')->on('survey')
->onDelete('cascade')
->onUpdate('cascade');
});
}
here are the two relation:
public function survey()
{
return $this->belongsToMany(Survey::class, 'survey_user')
->withPivot('status')
->withTimestamps();
}
public function user()
{
return $this->belongsToMany(User::class, 'survey_user')
->withPivot('status')
->withTimestamps();
}
I'm just trying to get all the users who have survey assigned in their pivot.
$user = new User();
var_dump($user->survey()->get());
I'm just trying to get all the users who have survey assigned in their pivot.
To get all Users where the survey relationship exists, your code would look like this:
$users = User::has('survey')->get();
If you need the survey relationship loaded on the models when you use them, then add with() to eager load the relationship:
$users = User::has('survey')
->with('survey')
->get();
Here, in the end, the user_id should not be null.
The reason it was searching with a null user id is because you are searching with a new User instance that hasn't been saved to the database. This is your code with the problem:
$user = new User();
var_dump($user->survey()->get());
Since $user is a new object that hasn't been saved to the database it doesn't have an id. When you call $user->survey() it builds a query to search survey_user where the user id is null.
I have next pivot table:
Schema::create('coach_user', function(Blueprint $table)
{
$table->integer('coach_id')->unsigned()->index();
$table->foreign('coach_id')->references('id')->on('coaches')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->tinyInteger('rank');
});
In User.php:
public function coaches()
{
return $this->belongsToMany(\App\Coach::class)->withPivot('rank');
}
How I can receive coaches of user with some rank? Something like this:
$user->coaches->where('rank',1)->get().
use wherePivot() to filter the results returned by belongsToMany.
$user->coaches()->wherePivot('rank',1)->get();
Use wherePivot for pivot columns and relation as method:
$user->coaches()->wherePivot('rank',1)->get().
So I am trying to figure a solution to this but not sure exactly how to do this. I have a table that stores all the shows that happen. In a given show I can have multiple providers attend that show. A provider could also attend many shows as well. So how do I store this in the DB and do the eloquent relationship?
Show Schema
Schema::create('shows', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('number')->unsigned();
$table->dateTime('airDate');
$table->string('podcastUrl')->nullable();
$table->timestamps();
});
Provider Schema
Schema::create('providers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('shortName')->nullable();
$table->string('image')->nullable();
$table->string('social')->nullable();
$table->timestamps();
});
Would I store the provider_id in the shows schema?
Update 1
So I created a new migration for a pivot table
Schema::create('provider_show', function (Blueprint $table) {
$table->integer('provider_id')->unsigned()->index();
$table->foreign('provider_id')->references('id')->on('providers')->onDelete('cascade');
$table->integer('show_id')->unsigned()->index();
$table->foreign('show_id')->references('id')->on('shows')->onDelete('cascade');
$table->primary(['provider_id', 'show_id']);
});
Then in the show model I created the following
public function providers()
{
return $this->belongsToMany(Provider::class);
}
Now when I am saving a new show I added a multiselect to select the providers I want
$show = new Show;
$show->name = $request->name;
$show->number = $request->number;
$show->airDate = $request->airDate;
$show->podcastUrl = $request->podcastUrl;
$show->providers()->attach($request->providerList);
$show->save();
Session::flash('message', "Created Successfully!");
return back();
Then when I save I get the following error
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: provider_show.show_id (SQL: insert into "provider_show" ("provider_id", "show_id") select 1 as "provider_id", as "show_id" union all select 2 as "provider_id", as "show_id")
Create a provider_show migration which will act as your pivot table.
This table would contain both provider_id and show_id which will provide the many-to-many relationship between those entities.
Then on your Provider model you can provide a shows() method which returns a BelongsToMany relationship.
// In your Provider model
public function shows()
{
return $this->belongsToMany('App\Show');
}
Note that Laravel by default looks for a pivot table name based alphabetically on the two relationships.
You can also add the inverse on your Show model by providing a providers() method that also returns a BelongsToMany relationship.