Saturday, April 15, 2017

laravel relation suddenly is in reverse when running query (parent/child)

so i have 2 tables orders and factors(invoice)

here is the how i've defined relations in models

Order.php :

function Factor(){
    return $this->hasOne('App\Factor');
}

Factor.php :

function Order(){
    return $this->belongsTo('App\Order');
}

this is how my database is :

orders : id , other_stuff
factord : id , order_id , other_stuff

it was working fine until i've added some unrelated lib to my project using composer (i dont know if it has to do anything with the problem) and after it was done suddenly i laravel seems to think there should be a factor_id in the orders table ... for the life of me i cant figure out what happend

so i was running this query before without problem

    $query   = Order::whereHas('Factor' , function($q) use ($facor_cond) {
        return $q->where($facor_cond);
    } )->get();

now im getting this error

Column not found: 1054 Unknown column 'orders.factor_id' in 'where clause' 

and here is the query thats is running

SQL: select * from `orders` where exists (select * from `factors` where `orders`.`factor_id` = `factors`.`id` and `factors`.`deleted_at` is null) and `orders`.`deleted_at` is null

shouldn't this be other way around based on the relation i've defined ? i mean i've said order->hasOne->Factor so it should look for order_id in the factors



via hretic

Advertisement