mardi 11 octobre 2016

Laravel Eloquent, How to define tables relation with formula?

On Laravel Eloquent,

How can I define relation condition with something that not exist on the table but calculated from a value in the table.

For example :

quarters                transactions
 _________ _________    _________ ___________
|   name  |  desc   |  |   id  |  date        |
 _________ _________    _________ ___________
|     1   | Jan-Mar |  |     1   | 2016-04-01 |
|     2   | Apr-Jun |  |     2   | 2016-05-01 |
|     3   | Jul-Sep |  |     3   | 2012-07-21 |
|     4   | Oct-Dec |  |     4   | 2014-01-31 |
 _________ _________    _________ ___________

It's work fine with this

SELECT 
FROM transactions tx
INNER JOIN quarters q ON q.name = ((MONTH(tx.date)+2)/3)

Quarters.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Quarters extends Model{

}

Transactions.php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Transactions extends Model{

    public function quater(){
        return $this->belongsTo('App\Models\Quarters' , '????', 'name') ;
    }
}

What should I define in my model in order to be able to do: Transactions::where("some_field", "some_value")->with("quater")->get()



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire