I have made two tables Inventories and Inventory_images. Primary key of Inventory table is the foreign key of inventory_images table now i am trying to fetch all the images of same inventory but getting error.
Here's my code
Inventory Model:
/**
* The table name that should be hidden from other modules
*/
protected $table = 'inventories';
protected $PrimaryKey = 'id';
public function test(){
return $this->belongsTo('App\InventoryImage', 'i_id');
}
InventoryImage Model:
protected $table = 'inventory_images';
protected $PrimaryKey = 'id';
public function inv_det(){
return $this->belongsTo('App\Inventory', 'id');
}
Controller:
$inventory = Inventory::with('test')->orderBy('id', 'DESC')->paginate('10');
dd($inventory);
Can some one please help me find out the issue
You are making some mistakes in your code which you should resolve first (and which might help you solve your problem).
First, the variable name to overwrite the primary key should be $primaryKey and not $PrimaryKey (variable names normally always start with a small letter.
This should not have any influence though, since Laravel assumes the primary key field to be named id anyway.
More importantly, you are in both cases using the belongsTo method, although in one case it should be hasMany. In a 1-n relation the parent model should return the hasMany relationship, and the child model (which holds the column with the foreign key) the belongsTo.
Furthermore, the second argument of the hasMany or belongsTo method is the foreign key column name, in case it is different of the snake case representation of the model (appended by _id). So IF your inventory_images table has a differently named foreign key column other than inventory_id, you need to pass along the second argument with the correct name. I assume that your foreign key name is i_id, so you need to pass it to both functions.
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many
Please check if this works:
/**
* The table name that should be hidden from other modules
*/
protected $table = 'inventories';
protected $primaryKey = 'id';
public function test(){
return $this->hasMany('App\InventoryImage', 'i_id');
}
And the child table:
protected $table = 'inventory_images';
protected $primaryKey = 'id';
public function inv_det(){
return $this->belongsTo('App\Inventory', 'i_id');
}
Related
I have a model User in Laravel 6.5.1.
class User extends Authenticatable
{
use Notifiable;
public $table = 'usuario';
public $primaryKey = 'cif_usu';
public $incrementing = false;
public $timestamp = false;
//...
}
However, when I'm trying to select a user, I'm getting the following error:
SQLSTATE[42703]: Undefined column: 7 ERROR: column "id" does not exist
LINE 1: select * from "usuario" where "id" = $1 limit 1 ^ (SQL: select
* from "usuario" where "id" = 24 limit 1)
How can I rename the id column?
Edit:
I changed:
public $primaryKey = 'cif_usu';
to:
protected $primaryKey = 'cif_usu';
and the result is the same
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention:
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'key';
Read more about Laravel - Primary Keys
The visibility of the $primaryKey attribute should be protected. I think without traffic that change you aren't actually overriding the primary key in the base Model class.
If that's not the case it may be useful to see the code that triggers this query
Put primarykey and table as protected.
protected $table = 'usuario';
protected $primaryKey = 'cif_usu';
public $incrementing = false; //only if your primary key is an assignable field,not auto incremented
You can use model as
DB::table('usuario')->where('cif_usu',$cif_usu)->first();
OR
DB::table('usuario')->find($cif_usu);
I've just started using Eloquent ORM (Without Laravel) and I am having issues with the many to many relationships.
I have a table where I store Families (Article categories), another one for the Articles, and a third one as a "pivot". I want to be able to get all the articles a Family has, and all the families an article belongs to. So I have coded this models.
Families
class Families extends Model {
public $table = 'Families';
public function Articles() {
return $this->belongsToMany('Articles', 'articles_families', 'families_id', 'articles_id');
}
}
Articles
class Articles extends Model {
public $table = 'Articles';
public function Families() {
return $this->belongsToMany('Families', null, 'articles_id', 'families_id');
}
}
Then I am trying to retrieve the data like this:
$families = Families::all();
echo $families[1]->Articles;
However, it just returns an empty array, when it should return a couple of articles. I have tripled checked that all the values are correct in the three tables. If I echo the Eloquent query debugger I can see that it is looking for a null value and I'm pretty sure that's the problem, but I don't quite know how to fix it. Here:
{"query":"select * from `Families`","bindings":[],"time":49.13},{"query":"select `Articles`.*, `articles_families`.`families_id` as `pivot_families_id`, `articles_families`.`articles_id` as `pivot_articles_id` from `Articles` inner join `articles_families` on `Articles`.`id` = `articles_families`.`articles_id` where `articles_families`.`families_id` is null","bindings":[],"time":38.93}
The null value is at the end of the last query.
I just found the solution myself. As my primary key columns are called Id, and Eloquent by default assumes the primary key is called id, I needed to override that by adding a class property protected $primaryKey = "Id"; and it now retrieves the data properly.
I have two models User and UserType declared as follows:
class User extends Model {
protected $table = 'user';
protected $primaryKey = 'user_id';
public function company() {
return $this->hasOne('App\Models\Company', 'company_id', 'company_id');
}
public function userType() {
return $this->hasOne('App\Models\UserType', 'user_type_id', 'user_type_id');
}
}
class UserType extends Model {
protected $table = 'user_type';
protected $primaryKey = 'user_type_id';
}
Now, I query the relationships using:
User::with('userType', 'company')->all()
Strangely, I get the company but userType is always null.
The MySQL query log shows that Laravel was able to get the user_type record.
The only difference between company and userType relationships are the data type of the primary keys. company.company_id is numeric while user_type.user_type_id is a string.
I think it is related to the data type of the keys however, I have a similar setup on Laravel 5.1 and it runs perfectly.
Laravel supports non-numeric primary keys but you need to set:
public $incrementing = false;
on your model class.
I corrected the issue by changing UserType definition to:
class UserType extends Model {
protected $table = 'user_type';
protected $primaryKey = 'user_type_id';
public $incrementing = false;
}
The first issue i notice with your relationship is that the first user_type_id you have passed to the hasOne function is wrong because you have the user_type_id as the primary key of the user_type table. The second argument of the hasone must be the foreign key of the parent table which is the user. So if you have anything like user_id in the user_type table use that instead.
But if thats not the case and user rather belongs to UserType then you have to change the hasOne to belongsTo.
So the belongsToMany relationship is a many-to-many relationship so a pivot table is required
Example we have a users table and a roles table and a user_roles pivot table.
The pivot table has two columns, user_id, foo_id... foo_id referring to the id in roles table.
So to do this we write the following in the user eloquent model:
return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');
Now this looks for an id field in users table and joins it with the user_id field in the user_roles table.
Issue is I want to specify a different field, other than id to join on in the users table. For example I have bar_id in the users table that I want to use as the local key to join with user_id
From laravel's documentation, it is not clear on how to do this. In other relationships like hasMany and belongsTo we can specify local key and foriegn key but not in here for some reason.
I want the local key on the users table to be bar_id instead of just id.
How can I do this?
Update:
as of Laravel 5.5 onwards it is possible with generic relation method, as mentioned by #cyberfly below:
public function categories()
{
return $this->belongsToMany(
Category::class,
'service_categories',
'service_id',
'category_id',
'uuid', // new in 5.5
'uuid' // new in 5.5
);
}
for reference, previous method:
I assume id is the primary key on your User model, so there is no way to do this with Eloquent methods, because belongsToMany uses $model->getKey() to get that key.
So you need to create custom relation extending belongsToMany that will do what you need.
A quick guess you could try: (not tested, but won't work with eager loading for sure)
// User model
protected function setPrimaryKey($key)
{
$this->primaryKey = $key;
}
public function roles()
{
$this->setPrimaryKey('desiredUserColumn');
$relation = $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');
$this->setPrimaryKey('id');
return $relation;
}
On Laravel 5.5 and above,
public function categories()
{
return $this->belongsToMany(Category::class,'service_categories','service_id','category_id', 'uuid', 'uuid');
}
From the source code:
public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
$parentKey = null, $relatedKey = null, $relation = null)
{}
This is a recently added feature. I had to upgrade to 4.1 because I was also looking for this.
From the API documentation:
public BelongsToMany belongsToMany(string $related, string $table = null, string $foreignKey = null, string $otherKey = null, string $relation = null)
The $otherKey and $relation parameters were added in 4.1. Using the $foreignKey and $otherKey parameters allows you to specify the keys on both sides of the relation.
The best way is set the primary key.
class Table extends Eloquent {
protected $table = 'table_name';
protected $primaryKey = 'local_key';
belongsToMany allows to define the name of the fields that are going to store che keys in the pivot table but the method insert always the primary key values into these fields.
You have to:
define in the method belongsToMany the table and the columns;
then using protected $primaryKey = 'local_key'; you can choose which value store.
I recently went through the same problem where I needed to have an associated table that used ID's to link two tables together that were not Primary Keys. Basically what I did was create a copy of my model that models the pivot table and set the Primary Key to the value that I wanted it to use. I tried creating a model instance, settings the primary key and then passing that to the relation but Laravel was not respecting the primary key I had set ( using the ->setPrimaryKey() method above ).
Making a copy of the model and setting the primary key feels a little bit 'hackish' but in the end it works as it should and since Pivot table models are generally very small I don't see it causing any problems in the future.
Would love to see a third key option available in the next release of Laravel that lets you get more specific with your linking.
I am just starting with ORM. I had a question, this is my tabel --
table a - (aid, aname, atag);
table b - (bid, aid, bname, .. );
It is One to Many relationship - that is One aid can belong to many bid but one bid can belong to only one aid.
So I was trying out this code, In the out put I want -- (bname,aname) for all the records.
A model --
class A extends Eloquent {
protected $table = 'a';
protected $primaryKey = 'aid';
public function brelation() {
$this->belongsToMany('B','aid');
}
}
B model --
class B extends Eloquent {
protected $table = 'b';
protected $primaryKey = 'bid';
public function getANames() {
$this->hasOne('A','aid');
}
}
In Controller --
foreach(B::with('getANames')->get() as $b_item){
echo $b_item->bname." , ".$b_item->aname;
}
Couple of points to clarify --
1) I have to specify the foreign key to make sure they map. Because in my actual case they are named differently.
2) I am using Laravel 4.
Can someone show me what I did wrong and how I can get the desired result.
===== Update =====
class A extends Eloquent {
protected $table = 'a';
protected $primaryKey = 'aid';
public function brelation() {
$this->belongsTo('B','aid');
}
}
I still cannot access the aname column i.e ($b_item->aname) in the controller.
A couple of things you should be aware of:
If you have a custom primary key, you need to set the $primaryKey property on your eloquent models to the primary keys you have in the DB.
You can't mix and match belongsToMany relationships with anything other than belongsToManys. A belongsToMany is exclusively for the case where you have two tables that are connected by a pivot table. In your case, B belongsTo A, and A hasMany B.