【问题标题】:Compare two different columns from two different tables and show other column's data from either table using orm relationship in laravel 5.4比较两个不同表中的两个不同列,并使用 laravel 5.4 中的 orm 关系显示任一表中其他列的数据
【发布时间】:2017-09-18 08:45:34
【问题描述】:

我有两个模型,一个是Companies,另一个是InterviewsCompanies 表的主键是 Company_details_id,此键在 Interviews 表中用作外键 f_company_id

现在我的问题是如何比较两个键值,如果我的条件为真,它将返回 companies 表中的列 company_name

我的公司模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Companies extends Model
{
 protected $table = 'company_details';

  protected $primaryKey = 'company_details_id';


  public function interviews()
  {
      return $this->hasmany('App\Interviews', 'f_company_id');
  }


}

我的面试模型:

<?php

use Illuminate\Database\Eloquent\Model;


class Interviews extends Model
{
 protected $table = 'interview_schedule';

 protected $primaryKey ='schedule_id';



 public function getCompanies()  
   {
        return $this->belongsto('App/Companies'); 
    }


}

我的控制器:

<?php

namespace App\Http\Controllers;


use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Companies;
use App\Interviews;


class PracticeController extends Controller

{
   public function getAll()
   {

    $getcompany=Companies::where('Companies.company_details_id','=','Interviews.f_company_id')
                 ->select('company_name')->get();

      echo $getcompany; 

   }


}

拜托,伙计们,我需要在 laravel 5.4 中使用雄辩的 orm 得到一个明确的答案

【问题讨论】:

    标签: php mysql laravel laravel-5 orm


    【解决方案1】:

    您要达到的目标并不完全清楚,但这里有一些指导方针。

    首先,您似乎将“一家公司可以进行多次采访”和“一次采访只能属于一家公司”作为您的关系。大多数情况下,您已经在模型中正确设置了这些。

    由于您的关系,您的“getAll”查询应该是:

    $companies = Company::with(['interviews'])->select(['company_name'])->get();
    

    然后您就可以相对轻松地遍历它们:

    foreach($companies as $company)
    {
      foreach($company->interviews as $interview) {
        // Do something with $interview
      }
    }
    

    使用 with 调用关系“采访”,它根据假定的键自然地执行两个表之间的所有 where 子句。由于您似乎有非标准主键,因此您需要更详细地定义 hasMany 和 belongsTo。

    public function interviews()
    { 
      return $this->hasMany(Interview::class, 'f_company_id', 'company_details_id');
    }
    

    我建议将您的模型称为 Company 和 Interview,而不是复数版本。这是因为单个记录涉及单个公司(基于您所写内容的假设)。从长远来看,您会发现它不那么令人困惑。

    【讨论】:

      【解决方案2】:

      我想你可以试试这个:

       DB::table('interview_schedule')
       ->select('company.company_name')
       ->join('company','company_details.company_details_id','=','interview_schedule.f_company_id')
       ->where('interview_schedule.f_company_id','=','company.company_details_id')
       ->get();
      

      希望这对你有用!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        • 2021-08-27
        • 1970-01-01
        相关资源
        最近更新 更多