dsjuimtq920056 2019-03-16 10:59
浏览 147

Laravel Eloquent关系获取第三个表/关系值

I have 3 tables in a database

  1. Transaction {'id','bill_id','remark'}
  2. Bills {'id','third_party','amount'}
  3. ThirdParty {'id','company_name',remark}

The 'transaction' table has column bill_id coming from 'Bills' and Bills table has 'third_party' column which connected to ThirdParty table column -> 'id'

So here I am trying to fetch company_name using laravel eloquent relation

My Transaction model:

public function Bills()
{
    return $this->hasOne('App\Bills','id','bill_id');
}

Bills:

public function third_party()
{
    return $this->belongsTo('App\ThirdParty','third_party','id');
} 

I am getting null value for company_name

enter image description here

Here is the query i am using

Transaction::with('Bills.third_party')->get();

And i have corrected in question (third_party_name) to company_name column name i wrote here was my old join query name which is visible in screenshot, basically i am trying to fetch company name.

  • 写回答

1条回答 默认 最新

  • duanjihe5180 2019-03-16 11:24
    关注

    Are you able to show all of your code? How does company_name get set to third_party_name?

    You could probably also gain a lot by sticking to the laravel "conventions" or "suggested naming", this will give you a lot of functionality for free, and make your code easier to read, write and debug.

    eg. Your relationship method names (Bills(), third_party()), but more importantly if you name your table fields in the "laravel way", you will get easier eloquent relationships as there will be no need to define the foreign keys etc.

    I would be setting this up similar to:

    1. Transaction {'id','bill_id','remark'}
    2. Bills {'id','third_party_id','amount'} <- note the third_party_id
    3. ThirdParty {'id','company_name',remark}

      class Transaction extends Model
      {
          public function Bills()
          {
              return $this->hasOne('App\Bills');
          }
      }
      
      class Bills extends Model
      {
          public function ThirdParty()
          {
              return $this->belongsTo('App\ThirdParty);
          }
      }
      

    You should also define the inverse relationships.

    It would be very beneficial to see the full code to see where the issue is.

    评论

报告相同问题?

悬赏问题

  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀