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)'));
}
Related
I created a relationship in my 'Event' model called 'Type'.
public function type()
{
return $this->belongsTo('Types');
}
In my 'Types' database, I have several elements. My relationship returns them all, and I would like to know if it was not possible, directly in the relation, to indicate that I only want the types with the column "parent_id" 1.
Thank you very much
If I understand you correctly, you want to add a where clause to your relationship. You can do this right in the definition. I guess this isn't very clear in the laravel 5.5 docs.
Another note, if your model is called "Type" as you stated in the question, then your relationship should use this name as well:
public function type()
{
return $this->belongsTo('App\Type')->where('types.parent_id', 1);
}
... or with a namespace...
use App\Type;
...
public function type()
{
return $this->belongsTo(Type::class)->where('types.parent_id', 1);
}
I need to get all appeals, that have appeal_stage.expiration_date less than NOW().
Now I have following solution:
public function scopeExpired($query) {
$query->join('appeal_stage', 'appeals.id', 'appeal_stage.appeal_id')
->where('appeal_stage.expiration_date', '<=', new Expression('NOW()'));
}
but resulted model dump shows that joined table is recognized as pivot table:
So, I want to ask - Is there some more convenient way to perform this request?
My suggestions is use Illuminate\Database\Eloquent\Relations\Pivot somehow, bu I do not quiet understand, how Pivot can be used here.
UPD 1
Models has next relations:
public function stages()
{
return $this->belongsToMany(Stage::class)->withPivot('prolongated_count', 'expiration_date')->withTimestamps();
}
public function appeals() {
return $this->belongsToMany(Appeal::class);
}
You should be able to do something like this:
$appeal->stages()->wherePivot('expiration_date', '<', $now)->get()
You should create relationship in appeal model
public function stages()
{
return $this->belongsToMany(Stage::class,'appeal_stage','appeal_id','stage_id')->wherePivot('expiration_date','<',Carbon::now())->withTimestamps();
}
In belongs To Many relationship second argument is your Pivot table name
I have a model Page and many models called SomethingSection - they're connected through a polymorphic m-m realtionship and the pivot has an additional column 'position'.
I need to write a relationship (or accessor maybe?) on the Page model that will return a collection of all connected Sections, regardless of their model (read: table).
My models:
class Page extends Model {
public function introSections()
{
return $this->morphedByMany(IntroSection::class, 'pagable');
}
public function anotherSections()
{
return $this->morphedByMany(AnotherSection::class, 'pagable');
}
}
class IntroSection extends Model {
public function pages()
{
return $this->morphToMany(Page::class, 'pagable');
}
}
class AnotherSection extends Model {
public function pages()
{
return $this->morphToMany(Page::class, 'pagable');
}
}
The pivot column looks like this:
pagables
-page_id
-pagable_id
-pagable_type
-position
I'm looking for a way to call a method/attribute on the Page model and get all the connected sections in a single collection, sorted too. What would be a good way to go about this?
I understand that the connected sections do not have the same interface, but in my case that's not a problem at all (in terms of what I will do with the data).
I also understand that relationships perform a separate query (for each relationship), so getting all of them with 1 query is impossible (also different interfaces would be a problem here). And for the same reason the sorting will need to be done on the collection level, not in query.
How could I make this as maintainable as possible and preferably with as small a performance hit as possible.
Thanks in advance.
You can use withPivot() method after your relationship to get the pivot columns with relation like this:
class Page extends Model {
public function introSections()
{
return $this->morphedByMany(\HIT\Models\Sections\IntroSection::class, 'pagable')
->withPivot(['position']);
}
public function anotherSections()
{
return $this->morphedByMany(AnotherSection::class, 'pagable');
}
}
class IntroSection extends Model {
public function pages()
{
return $this->morphToMany(Page::class, 'pagable')
->withPivot(['position']);
}
}
and you can use collection's sortBy to sort the collection by using sortBy() method like this:
$sorted_collection = IntroSection::pages->sortBy('pagables.position');
UPDATE:
You can use collection's combine() method to get all the relationships like this, add this method inside your Page Class:
public function getAllSections()
{
return $this->introSections->combine($this->anotherSections-toArray())
->sortBy('pagables.position'):
}
Hope this helps!
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 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');
}
```