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');
}
Related
I want to get POSTS from the CATEGORIE i do the relationship HasMany/belongsTo but it gives me error.
Categorie.php
public function posts(){
return $this->hasMany('App\Post');
}
Post.php
public function category(){
return $this->belongsTo('App\Category');
}
SiteController.php
public function getPostsOfCategory($slug){
$categorie=Categorie::where('slug',$slug)->first();
$posts= $categorie->posts()->paginate(4);
$categories=Categorie::all();
return view('site.blog',['posts'=>$posts,'categories'=>$categories]);
}
First of all you called model Categorie but using Category.
return $this->belongsTo('App\Category');
->
return $this->belongsTo('App\Categorie');
This might be not the whole solution.
After that check the name of foreign key column in posts table. And change/add it in database or pass as the second parameter to belongsTo() relation.
The mistake is in your SiteController
public function getPostsOfCategory($slug)
{
$categorie=Categorie::where('slug',$slug)->first();
$posts= $categorie->posts;
$categories=Categorie::all();
return view('site.blog',['posts'=>$posts,'categories'=>$categories]);
}
I would like to get many "badges" to one "company"
I have 3 tables companies, badgy, badgy_company as pivot table.
What should I try/do? Can someone give me a hint or something?
company.blade.php
#foreach($listings->badgy as $type)
<span class="label label-default">{!! $type->title !!}</span>
#endforeach
Badgy.php
class Badgy extends Model{
protected $table = 'badgy';
public function badgy()
{
return $this->hasMany(Company::class);
}
If I remove protected $table = 'badgy'; I get error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'MYDATABASE.badgies' doesn't exist
Company.php
public function badgy()
{
return $this->belongsToMany(Badgy::class);
}
In page controllers I try:
$listings = Company::find($id);
$listings = Company::query()->get();
If I need to provide any more info, please, just ask.
You are not following the Laravel naming conventions. As a result, the default values used for relations by the framework don't work. You will have to set them manually as follows:
class Badgy
{
protected $table = 'badgy'; // Laravel default would be 'badgies'
public function companies()
{
return $this->belongsToMany(Company::class, 'badgy_company', 'category_id', 'company_id');
}
}
class Company
{
protected $table = 'companies'; // optional as the default is the same
public function badgies()
{
return $this->belongsToMany(Badgy::class, 'badgy_company', 'company_id', 'category_id');
}
}
Please also have a look at another answer of mine where I explain some important pieces regarding relationships and naming conventions. Because in a perfect scenario you would have the following tables and columns:
companies:
- id
- name
badgies:
- id
- title
badgy_company:
- id
- badgy_id
- company_id
Which would allow your models to look like this:
class Badgy
{
public function companies()
{
return $this->belongsToMany(Company::class);
}
}
class Company
{
public function badgies()
{
return $this->belongsToMany(Badgy::class);
}
}
I'm trying to do browser game like Tribal Wars in Laravel.
I want to get building level by using $wioska->buildings->Tartak->level, but something not working:
This is my Building model:
class Building extends Model
{
protected $table = 'budynki';
public function Tartak(){
return $this->hasOne('App\Tartak');
}
}
Wioska (village) model:
class Wioska extends Model
{
protected $fillable = ['name', 'user_id'];
protected $table = 'wioski';
public function user(){
return $this->belongsTo('App\User');
}
public function buildings(){
return $this->hasOne('App\Building');
}
}
And this is my Tartak model:
class Tartak extends Model
{
protected $table = 'budynki';
public function level(){
$u = Auth::user();
$id = $u->wioska->id;
return DB::table('budynki')->where('wioska_id', $id)->first();
}
}
Migration "budynki":
public function up()
{
if(!Schema::hasTable('budynki')) {
Schema::create('budynki', function (Blueprint $table) {
$table->integer('town_hall')->default(1);
$table->integer('iron')->default(0);
$table->integer('wood')->default(0);
$table->integer('stone')->default(0);
$table->integer('bread')->default(0);
$table->integer('wioska_id');
$table->foreign('wioska_id')->references('id')->on('wioski');
});
}
}
1) It's always good to check for a null entity before trying to call its methods. Example, if $wioska->buildings is null or wioska has no buildings, or buildings have no Tartak, then the rest of the line will throw errors.
2) level() is a method and since its not an authentic Laravel relationship, you will need to use it as a method, example - $wioska->buildings->Tartak->level()
level is not property as per your model, so you have to try as below
$wioska->buildings->Tartak->level()
Now I've got
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'budynki.building_id' in 'where clause' (SQL: select * from budynki where budynki.building_id is null and budynki.building_id is not null limit 1) error
I just want to get tartak level from budynki table: https://i.imgur.com/zoTx5tE.png .
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);
}
}
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.