I have the following table structure
turns
id
orders_payments
id
turn_id
order_id
orders
id
And I want to get all orders related to a turn
so
Class Turn{
public function orders(){
return ????
}
}
How can you achieve that?
I tried the hasmanythrough but it only works when the relations are in cascade
Thanks!
I wonder why you make your life hard and call your model Turn and the pivot table order_payment ?
Anyway, you want this:
// Turn model
public function orders()
{
return belongsToMany('Order', 'order_payment');
// in case you would like to call your fkeys differently, use this:
// return belongsToMany('Order', 'order_payment', 'payment_id', 'order_whatever_id');
}
// Order model
public function turns() // or payments() ?
{
return belongsToMany('Turn', 'order_payment');
}
You can use
public function orders()
{
return $this->belongsToMany('Order');
}
Then you can do
$orders = Turn::find(1)->orders;
As #lowerends points out, this is a BelongsToMany relationship, since I was using the orderPayments table for more things I didn't notice it until he said, so finally the solution is the following
```
public function orders(){
return $this->belongsToMany('Order','orders_payments','turn_id','order_id');
}
```
Related
hi i have many to many polymorphic Relation
When I use the sync method to insert data in the interface table, I encounter this error. What is the problem?
controller code:
$job_create->skills()->sync($request['skill']);
job model:
public function skills(){
$this->morphMany(Skil::class,'skillables');
}
skill model:
public function jobs()
{
return $this->morphedByMany(Job::class, 'skillables');
}
first make sure that given Skil::class is correct i think it must be Skill::class
public function skills(){
return $this->morphMany(Skill::class,'skillables');
}
the error says that $job_create->skills() is null you can test it with dd();
dd($job_create->skills()->get());
if the problem didn't solved just study the documentation:
https://laravel.com/docs/9.x/eloquent-relationships#many-to-many-polymorphic-relations
Relationships should always return the relation.
public function skills(){
return $this->morphMany(Skil::class,'skillables');
}
I'm trying to add a relation to my Booking model. I already have a relation that looks like this:
public function vehicle() {
return $this->belongsTo(Vehicle::class);
}
Which works on the column bookings.vehicle_id. However, now I'm adding another column called bookings.billed_vehicle_id which will "override" the vehicle_id if it's not null. So I want to do something like this:
public function billedVehicle() {
return $this->belongsTo(Vehicle::class,DB::raw('coalesce(billed_vehicle_id,vehicle_id)'));
}
Is this possible?
And if not possible with belongsTo can I somehow create a custom relation that'll support this?
belongsTo() returns a query builder so you can go ahead and just chain ->whereRaw() on the end of it:
public function billedVehicle() {
return $this->belongsTo(Vehicle::class)
->whereRaw(DB::raw('coalesce(billed_vehicle_id,vehicle_id)'));
}
I have the following schema set up:
users:
id
departments:
id
department_user:
id
department_id
user_id
I also have the following relationships set up:
User Model
public function departments()
{
return $this->belongsToMany('App\Resources\Eloquent\Models\Department', 'department_users');
}
Department Model
public function users()
{
return $this->belongsToMany(User::class, 'department_users');
}
For some reason, when I am trying to access through the user model $user->departments, it doesn't work - but $department->users does.
Outputting the eloquent query is as follows:
select `departments`.*, `department_users`.`user_id` as `pivot_user_id`, `department_users`.`department_id` as `pivot_department_id` from `departments` inner join `department_users` on `departments`.`id` = `department_users`.`department_id` where `department_users`.`user_id` is null
I can't seem to figure out why it is looking to see if department_users.user_id is null, when it should be looking for the user's id.
Any ideas?
Why don't you set up your models like it is suggested in the documentation here:
So your models would look something like this:
User Model
public function departments()
{
return $this->belongsToMany('path\to\your\model\Department');
}
Department Model
public function users()
{
return $this->belongsToMany(path\to\your\model\User);
}
Eloquent will join the two related model names in alphabetical order.So you don't need extra arguments when defining your relationship and Laravel also by default, makes model keys present on the pivot object. And then you can do something like this:
$department = path\to\your\model\Department::find(1);
foreach ($department->users as $user) {
echo $user;
}
For some reason, if I make the relationship the following - it works.
return $this->belongsToMany(Department::class, 'department_users')->orWhere('department_users.user_id', $this->id);
If anyone knows why, please let me know
I have 3 tables: orders, codes, events
I want to be able to pull all events that an order has, but there's an intermediary table that acts as a pivot table. I've been trying to use hasManyThrough and belongsToMany (along with withPivot) without any luck.
Examples:
public function events()
{
return $this->belongsToMany('events'); // tried this, fails
return $this->hasManyThrough('events', 'codes'); // tried this, fails
return $this->hasManyThrough('events', 'codes', 'event_id', 'id'); // tried this, fails
}
Any pointers would be great!
That's a belongsToMany setup. First, the first parameter is the name of the related class. Second, since your pivot table doesn't follow the Laravel naming conventions, you need to specify the name of the pivot table in your relationship definition:
public function events()
{
// first parameter is the name of the related class
// second parameter is pivot table name
return $this->belongsToMany(Event::class, 'codes');
}
With this setup, you can do:
// get an order
$order = Order::first();
// has all the events related to an order
$events = $order->events;
There are many ways to do this. I will show a one you can get it done.
In Order.php model
public function codes(){
return $this->has('App\Http\Code');
}
In Code.php model
public function orders(){
return $this->belongsTo('App\Http\Order');
}
public function events(){
return $this->hasMany('App\Http\Event');
}
In Event.php model
public function codes(){
return $this->belongsTo('App\Http\Code');
}
Then in you Controller, call them to get required data.
In your case you can do it like below:
$orders = Order::with(['codes' => function($q){
$q->with('events');
})->get();
May be you can get them with nested manner(not sure about this because i didn't tried before posting):
$orders = Order::with('codes.events')->get();
put return $orders; in your controller to see the query.
Enjoy!
I'm just getting started with Laravel so please forgive any noobness.
I have a User and Order model, a user has many orders:
# Inside User model
public function orders()
{
$this->hasMany('Order');
}
# Inside Order
public function user()
{
return $this->belongsTo('User');
}
// Not sure if this is upsetting anything (also in Order)
public function products()
{
return $this->belongsToMany('Product');
}
So I think I have the above right.
But when I do this:
$users = User::with('orders')->find(1);
return $users;
I get Call to a member function addEagerConstraints() on null.
However, if I do it the other way around, it works great:
$orders = Order::with('User')->get();
return $orders;
What am I doing wrong / what don't I understand?! Or is my problem bigger than I think?
Database:
The problem is you don't have return for your orders relationship. It should be:
public function orders(){
return $this->hasMany('Order');
}
You should also use your relationships case sensitive. you showed:
$orders = Order::with('User')->get();
is working, but you should rather use
$orders = Order::with('user')->get();
to avoid extra queries to your database in future
For anyone else that runs across this, I was having the same issue, but my problem was that I had the foreign/local keys swapped. Example:
// This is correct for hasX relationships
public function user() {
return $this->hasOne('App\Models\User', 'user_id', 'local_key_user_id');
}
// This is correct for belongsTo relationships
public function user() {
return $this->belongsTo('App\Models\User', 'local_key_user_id', 'user_id');
}
Notice that for hasX relationships, the foreign key is the second parameter, and the local key is the third. However, for belongsTo relationships, these two are swapped.
Probably doesn't answer this particular question but it relates to the title. I had the same issue here is the wrong query
$offer = Offer::with([
'images:name,id,offer_id',
'offer_options:offer_option,value,id,offer_id',
'user:id,name,avatar'])
->select(['id', 'views', 'type', 'status'])
->where('id', $id)->get();
the model look like this
class Offer extends Model {
function user(): BelongsTo {
return $this->belongsTo(User::class);
}
}
The User
class User extends ..... {
function offer(): HasMany {
return $this->hasMany(Offer::class);
}
}
The issue with the query is I was not selecting user_id, i.e in my select function user_id column was not included and that is why I was getting null for user
according to Laravel docs
When using this feature, you should always include the id column and
any relevant foreign key columns in the list of columns you wish to
retrieve.
So the correct query is
$offer = Offer::with([
'images:name,id,offer_id',
'offer_options:offer_option,value,id,offer_id',
'user:id,name,avatar'])
->select(['id', 'views', 'type', 'status','user_id'])
->where('id', $id)->get();