doubijiao2094
2016-10-12 06:18
浏览 46
已采纳

Laravel Eloquent,如何用公式定义表关系?

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()

note: I want to do this without modify table structure.

图片转代码服务由CSDN问答提供 功能建议

On Laravel Eloquent,

如何定义关系条件与 表中不存在但是从表中的值计算。

例如:

 季度交易
 _________ _________ _________ ___________  
 | 名字|  desc |  |  id | 日期| 
 _________ _________ _________ ___________ 
 |  1 |  Jan-Mar |  |  1 |  2016-04-01 | 
 |  2 |  4月 -  6月|  |  2 |  2016-05-01 | 
 |  3 | 七月至九月 |  3 |  2012-07-21 | 
 |  4 | 十月至十二月|  |  4 |  2014-01-31 | 
 _________ _________ _________ ___________ 
   
 
 

这可以正常使用

  SELECT \  nFROM事务tx 
INNER JOIN四分之一q ON q.name =((MONTH(tx.date)+2)/ 3)
   
 
 

Quarters.php

 &lt;?php 
namespace App \ Models; 
use Illuminate \ Database \ Eloquent \ Model; 
class Quarters扩展Model {
 
} 
   
 
 

Transactions.php

  namespace App \ Models; 
use Illuminate \ Database \ Eloquent \ Model; 
class Transactions extends Model {
 \  n public function quater(){
 return $ this-&gt; belongsTo('App \ Models \ Quarters','????','name'); 
} 
} 
  <  / pre> 
 
 

我应该在模型中定义什么才能做到: Transactions :: where(“some_field”,“some_value”) - &gt; with(“ quater“) - &gt; get()

注意:我想在不修改表格结构的情况下这样做。 \ n

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题