Laravel Error: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias - eloquent

Having three tables, booking, category, pivot_booking.
In Booking model -
public function category()
{
return $this->belongsToMany(\Modules\Backend\Entities\Category::class, "pivot_booking","booking_id","category_id")->withPivot('count');
}
In Category model-
public function bookings()
{
return $this->belongsToMany(\Modules\Frontend\Entities\Booking::class, "pivot_booking","booking_id","category_id")->withPivot('count');
}
In my controller, I want to fetch data from both tables as
$booking = \Modules\Frontend\Entities\Booking::with('category')->where('id',$decrypted)->first();
But getting the following error:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'pivot_booking' (SQL: select pivot_booking.*, pivot_booking.booking_id as pivot_booking_id, pivot_booking.category_id as pivot_category_id, pivot_booking.count as pivot_count from pivot_booking inner join pivot_booking on pivot_booking.id = pivot_booking.category_id where pivot_booking.booking_id = 1255)
Need quick help.

Related

Entity Framework Core Can't Add Entity but can Select it

My problem is:
I can select a entity normally, but when a try to add it, i'm receiving the exception:
ORA-06550: linha 3, coluna 22:
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: linha 3, coluna 1:
PL/SQL: SQL Statement ignored
Context below:
My database: Oracle
Owner (schema that have the data): XXX
User on connect (user that have permissions to select, insert, etc): YYY.
I'm ensure the grants its ok. I can insert mannualy the data.
My Entity on my API it's declared like:
[Table("TABLE_NAME", Schema = "XXX")]
public class AnalyzeFeedback
Select ok
IQueryable<AnalyzeFeedback> analyzeFeedbacks = dbContext.AnalyzeFeedbacks;
var query = (from u in analyzeFeedbacks
select u);
var sql = query.ToSql();
var result = query.FirstOrDefault();
This select returns the first record of my table. Perfectly.
When I try to add a new record:
Insert problem:
Exception on SaveChanges
dbContext.AnalyzeFeedbacks.Add(feedback);
dbContext.SaveChanges();
On "SaveChanges" it's when i'm getting the error.
Sorry if i'm not clear enough on my explanation.
Also does AnalyzeFeedback have any reference properties/fields
This is exactly my problem man, thanks.
My entity have a property that not correctly tagged:
[ForeignKey("AnalyzeId")]
public Analyze Analyze { get; set; }
[NotMapped] <<< this!
public List<AnalyzeFeedbackBasement> Basements { get; set; }
When a tagged like "NotMapped", the insert occoured like expected.
Thanks for your reply Gullard!!

Spring Data JPA throwing No Results were returned for custom Insert Statement

I have a table say it Name(name,lock,timestamp). name column is Primary key and for inserting i am not using inbuilt save method with does insert/update. My Requirement is to just insert and not to update if there exist. so I wrote my custom query for inserting data. When i run the query it inserts data into table but throws exception saying Caused by: com.edb.util.PSQLException: No results were returned by the query.
I tried using my custom insert with with constraint on confict.
#Repository
public interface MyNameRepository extends JpaRepository<MyEntity, Long> {
#Query(value="INSERT into name(name,lock,updtedTime) values (?,?,?) on conflict ON CONSTRAINT unique_name do nothing",nativeQuery = true)
public void insertData(String name,int lock,Timestamp startTime);
}
I expect it should insert without any error.

Eloquent Relation with foreign key

I have issues by connecting to tables
I have 2 Model
First Model called PodioBorgerNotat with columns in the table called podio_borger_notats
id
user_id
item_id
app_item_id
borger_item_id (foreign key) 🔐
medarbejder_item_id
status
The second Model called PodioBorgerStamark with columns in the table podio_borger_stamarks
id
item_id (local key) 🔑
app_item_id
status
initials
name
I want to make a connection between PodioBorgerNotat and PodioBorgerStamark
so this is what I do in PodioBorgerNotat Model
public function borger()
{
return $this->belongsTo(PodioBorgerStamark::class, 'borger_item_id', 'item_id');
}
Now I want to output the result by executing this output
$borgernotater = PodioBorgerNotat::orderBy('created_at', 'acs')->orderBy('id', 'desc')->with('PodioBorgerStamark')->paginate(10);
This wont work and i get this error messsage
Call to undefined relationship [PodioBorgerStamark] on model [App\PodioBorgerNotat].
Your relation name is borger:
public function borger(){
...
}
You should call borger in with():
$borgernotater = PodioBorgerNotat
::orderBy('created_at', 'acs')
->orderBy('id', 'desc')
->with('borger')
->paginate(10);

Nested wherehas with different relation in Eloquent

Here is some relation between Eloquent classes in a Laravel 5 application:
B belongs to A
B has one C
Table are built with the correct foreign keys.
Here is a scope method of A:
public function scopeMyScope(Builder $query)
{
return $query->whereHas('B.C', function($q) {
$q->whereRaw("1=1");
});
}
If we call A::myScope()->get(), it results in an SQL error, because laravel built this query:
select * from "a" where (select count(*) from "b" where "a"."a.b_id" = "b"."id" and (select count(*) from "c" where "c"."b_id" = "b"."id" and 1=1) >=1 ) >= 1
The error is:
Illuminate\Database\QueryException with message 'SQLSTATE[42703]: Undefined column: 7 ERROR: column c.b_id does not exist
So, the query built is wrong because there is no c.b_id column (because B hasOne C, so the join column is in C). Am I doing something wrong or is it a bug in laravel's query builder?
From what I can understand, you need to do a nested whereHas, so:
public function scopeMyScope(Builder $query)
{
// b is the name of the relationship...
return $query->whereHas('b', function($q)
{
// c is the name of the relationship...
$q->whereHas('c', function()
{
$q->where(1, 1);
});
}
}
Does this solve your problem?

How to setup Eloquent Relationship for Laravel Zizaco/entrust to get Role Permissions?

In Zizaco/entrust's Laravel Entrust, how do you setup the Entrust class relationships with Eloquent so you can get the list of permissions a role has like so:
// get admin role
$adminRole = Role::find(1);
// get the permission of the admin role
$adminRolePermissions = $adminRole->permissions();
I've tried adding the following Eloquent relationships to the Role class:
class Role class {
public function permissions()
{
return $this->hasManyThrough('App\Permission', 'App\PermissionRole', 'role_id', 'permission_id');
}
}
With this, when I get an instance of a role and try to get its permissions like so:
$adminRolePermissions = $adminRole->permission();
this error occurs:
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'permission_role.id' in 'on clause' (SQL: select permissions.*,
permission_role.role_id from permissions inner join
permission_roles on permission_role.id =
permissions.permission_id where permission_role.role_id = 1)
Of course, I have already created the following models: PermissionRole for the permission_role table.
permission_role.id is invalid. Your table permission_role should have columns, named "permission_id" and "role_id" by default because of "Eloquent ORM Relationships".
May be you have override your Model's Primary Key name.
Please check that Config.entrust file has the same attributes as your Models have.