I have users table with id on it.
My project model has $fillable fields:
protected $fillable = [
'title',
'description',
'visibility_level',
'creator_id'
];
relationship:
public function user()
{
return $this->belongsTo('App\User');
}
In Users model relationship:
public function projects()
{
return $this->hasMany('App\Project');
}
Now creator_id is refering to user_id. I have set up my project model table with:
$table->foreign('creator_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
But then I try to store data, it still tried to add user_id:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'field list'
My store() method:
public function store(ProjectRequest $request)
{
$project = new Project($request->all());
Auth::user()->projects()->save($project);
flash()->success('Project have been created');
return redirect('news/');
}
Am I searching In wrong place or what? I dont understand why its "user_id" where is this "user_id" generated name comes from?
The user_id key comes from the name of your class (User). All laravel does is snake case it and append _id to it. To fix your issue, use the second, optional, parameter for hasMany on your User class:
public function projects()
{
return $this->hasMany('App\Project', 'creator_id');
}
This should solve your problems now but, to use the relationship the other direction, you'll also need to make some changes on your Project model. You have two choices:
Rename your relationship method:
public function creator()
{
return $this->belongsTo('App\User');
}
Override the key by passing it as second parameter to belongsTo:
public function user()
{
return $this->belongsTo('App\User', 'creator_id');
}
Given what you are trying to achieve, I'd recommend you go with the first option.
Related
I'm trying to do follow system without any laravel libray. I got this error when I submit form. How can I fix it? I think error is about my user model and my follow model relationship but I couldn't solve.
My error is:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'muzik.follows' doesn't exist (SQL: insert into follows
(following_id, follower_id, updated_at, created_at) values
(12, 30, 2021-04-02 22:32:50, 2021-04-02 22:32:50))
My User model contains the following relationship:
public function follows(){
return $this->hasMany('App\Models\Follow');
}
My User model contains the following relationship:
public function user(){
return $this->belongsTo('App\Models\User');
}
My controller is:
public function follow(Request $request){
$request->validate([
'follower_id'=>['required'],
'following_id'=>['required'],
]);
$follower_id = $request->follower_id;
$following_id = $request->following_id;
$save = Follow::create([
'following_id' => Auth::user()->id,
'follower_id' => $follower_id,
]);
if($save){
return back();
}else{
return back();
}
}
check your "Follow" model, you may needs specify table name with:
protected $table='tableWhereYouSaveFollows';
Did you check your migration I think you did not create the Follow table if you did try to Just specify your table in the model as such:
class follows extends Model{
public $table = "follow";
I think your follow table does not exist, first create your follow table and then add this to your follow model:
use Illuminate\Database\Eloquent\Model;
class Follow extends Model
{
protected $table="follows";
//---Guarded
protected $guarded = [];
//---User Function
public function user(){
return $this->belongsTo('App\Models\User');
}
}
I have struggled with my Laravel relationships.
So I have 3 tables:
Users
Countries
countries_user
As you can see relation is countries_user. Now every time gives error like:
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found:
1054 Unknown column 'countries.user_id' in 'where clause' (SQL: select
from countries where countries.user_id = 1 and countries.user_id is not null) in file
C:\xampp\htdocs\gManager\vendor\laravel\framework\src\Illuminate\Database\Connection.php
on line 671
I understand the problem is that it's looking in countries and not in countries_user. How to define where I want to search the relation?
Here is my User model
public function countries()
{
return $this->hasMany('App\Models\Countries');
}
And my Countries Model
public function users()
{
return $this->belongsToMany(User::class);
}
Try specifying the table name
public function users()
{
return $this->belongsToMany(User::class, 'countries_user');
}
And the inverse relation should also be belongsToMany
public function countries()
{
return $this->belongsToMany(Countries::class, 'countries_user');
}
And also specify the table property on Countries model
class Countries extends Model
{
protected $table = 'countries';
//...
}
The countries relationship should be belongsToMany too.
Instead of
public function countries()
{
return $this->hasMany('App\Models\Countries');
}
put
public function countries()
{
return $this->belongsToMany('App\Models\Countries');
}
Recently I've been trying to create Nova resource which depends on the other resource which provides the information for the main resource.
I have a table contest_entries which has the following fields:
id
contest_id
user_id
with the following relations
public function contest() : BelongsTo {
return $this->belongsTo(Contest::class, 'contest_id', 'id');
}
public function user() : BelongsTo {
return $this->belongsTo(User::class, 'user_id', 'id');
}
Also, i have a table contest_submissions with the following fields:
id
entry_id
task_id
comment
approved
declined
with the following relations:
public function entry() : BelongsTo {
return $this->belongsTo(ContestEntry::class, 'entry_id', 'id');
}
public function user() : BelongsTo {
return $this->entry->user();
}
public function contest() : BelongsTo {
return $this->entry->contest();
}
public function task() : BelongsTo {
return $this->belongsTo(Task::class, 'task_id', 'id');
}
I have no problem in fetching this data on the index and details view of Nova, everything 'just works', however, when I try to update the resource, I'm getting the error that user() or contest() is called on null.
I've tried the following,
return [
BelongsTo::make('Contest', 'contest', Contests::class)->exceptOnForms(),
BelongsTo::make('Task', 'task', ContestTasks::class)->exceptOnForms(),
BelongsTo::make('User', 'user', AccountUsers::class)->exceptOnForms(),
]
But for some reason, Nova is still trying to fetch these relationships ever when i explicitly tell it not to.
Any ideas are greatly appreciated, because it works everywhere, except on the update view (create view is explicitly disabled since the submissions are created by the user on the frontend)
You should also chain a hideWhenUpdating() constraint to it.
return [
BelongsTo::make('Contest', 'contest', Contests::class)
->hideWhenUpdating()
->exceptOnForms(),
BelongsTo::make('Task', 'task', ContestTasks::class)
->hideWhenUpdating()
->exceptOnForms(),
BelongsTo::make('User', 'user', AccountUsers::class)
->hideWhenUpdating()
->exceptOnForms(),
]
i am trying to save data in third table in many to many relation but
data is not saving
user model
public function Jobs()
{
return $this->belongsToMany('App\Models\Job','App\Models\Job_User','user_id','job_id');
}
job model
public function Users()
{
return $this->belongsToMany('App\Models\User','App\Models\Job_User','job_id','user_id');
}
controller for saving data in third table is
public function JobApplied(Request $request){
$applied= new Job_User();
$applied->user_id = Auth::id();
$applied->job_id = $request->job_id;
$applied->cv = $request->cv;
$applied->current_salary = $request->current_salary;
$applied->expected_salary = $request->expected_salary;
$applied->save();
return redirect('searchjobs');
}
code of third table is
class Job_User extends Model
{
protected $fillable = [
'user_id','job_id','cv','current_salary','expected_salary','status',
];
protected $table = 'jobs_users';
}
You're using the many-to-many relation incorrectly. You don't need a model for the intermediate table as Eloquent will handle it for you.
First of all, you need to define the relation in your models in a correct way. The second argument should be the name of the intermediate table, not the model. As you're using the default values for table name and foreign key column names, you can skip them and just do:
public function Jobs()
{
return $this->belongsToMany('App\Models\Job');
}
public function Users()
{
return $this->belongsToMany('App\Models\User');
}
If you want to have additional fields in the intermediate column, you need to define it when you define a relationship using withPivot() method:
public function Jobs()
{
return $this->belongsToMany('App\Models\Job')->withPivot('cv','current_salary','expected_salary','status');
}
public function Users()
{
return $this->belongsToMany('App\Models\User')->withPivot('cv','current_salary','expected_salary','status');
}
Now, if you want to link a Job with a User and set the fields in the intermediate pivot table, you should use save() method on your relation:
$job->users()->save($user, ['cv' => $request->cv, 'current_salary' => $request->current_salary]);
or
$user->jobs()->save($job, ['cv' => $request->cv, 'current_salary' => $request->current_salary]);
Once you have data saved in your database you can retrieve data from intermediate pivot table using the pivot attribute of related model, e.g.:
foreach($user->jobs as $job) {
echo $job->pivot->current_salary;
}
or
foreach($job->users as $user) {
echo $user->pivot->current_salary;
}
Check the docs for more information about handling many-to-many relationship with Eloquent: https://laravel.com/docs/5.1/eloquent-relationships#many-to-many
I have the following model relationships. If a user logs in as an employee, I want them to be able to get a list of employees for a their company and the roles they have been assigned:
class User {
// A user can be of an employee user type
public function employee()
{
return $this->hasOne('App\Employee');
}
//
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
class Employee {
// employee profile belong to a user
public function user()
{
return $this->belongsTo('App\User');
}
// employee belongs to a company
public function company()
{
return $this->belongsTo('App\Company');
}
}
class Company {
public function employees()
{
return $this->hasMany('App\Employee');
}
}
But the following query doesnt work. I get error Column not found: 1054 Unknown column companies.id in WHERE clause:
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles' => function ($query) use ($employee) {
$query->where('companies.id', '=', $employee->company_id)
->orderBy('users.created_at', 'desc');
}])->get();
The users and the employees table have a one to one relationship.
All employees have a base role type of employee in addition they may also have other roles such as manager, supervisor etc.
How do I write a query that gives me a company with all its employees and their roles?
I've tried to add a hasManyThrough relation to the Company model but that doesn't work either?
public function users()
{
return $this->hasManyThrough('App\User', 'App\Employee');
}
I think you're ring to get a list of coworkers for the current user and eager load the user and role?
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles')->find($employee->company_id);
Or perhaps:
$companyEmployees = Company::find($employee->company_id)->employees()->with('user.roles')->get();
$sorted = $companyEmployees->sortBy(function($employee){ return $employee->user->created_at; });
That might be a more direct route. Is your employee id in the user table or vice versa? The eloquent relationships are easy to set backwards.
Users::select('table_users.id')->with('roles')->join('table_employes', function($join) use ($employee) {
$join->on('table_employes.user_id','=','table_users.id')->where('table_employes.company_id', '=', $employee->company_id);
})->orderBy('tables_users.created_at')->get();
1. Create relationship for database table columns in migrtaion :
User Role
$table->foreign('user_id')->references('id')->on('users');
Users
$table->increments('id');
2. Create a model for each database table to define relationship
User.php (model)
public function userRoles()
{
return $this->hasOne('App\UserRoles', 'user_id', 'id');
}
Userroles.php (model)
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
3. Let controller handle database calls recommended to use REST api
Controller
use App\User;
use App\UserRoles;
class UserController extends Controller
{
public function index()
{
return User::with('userRoles')->orderBy('users.created_at', 'desc')->paginate(50);
}
}