2016-03-16 31 views
0

我在我的應用程序下表:Laravel嘗試查詢relatinship模型的hasMany

projects projects_plot_types

項目可以有很多的情節類型。我在項目模型中設置了以下關係。

/** 
* The plot types that belong to the project. 
* 
* @return Object 
*/ 
public function plotTypes() 
{ 
    return $this->hasMany('App\Models\Project\ProjectsPlotTypes'); 
} 

我希望能夠通過查詢它是在項目型號,以得到情節類型。

我已經試過這一點,但它不工作:

$project->with('plotTypes')->whereHas('plotTypes', function ($query) use ($row) { 
    $query->where('name', $row->plot_name); 
})->first()->plotTypes->first()->id; 

有人能指出我在正確的方向?

$result按照下面的評論的輸出是:

Project {#705 ▼ 
    #table: "projects" 
    #fillable: array:7 [▶] 
    +timestamps: true 
    #connection: null 
    #primaryKey: "id" 
    #perPage: 15 
    +incrementing: true 
    #attributes: array:10 [▶] 
    #original: array:10 [▶] 
    #relations: array:1 [▼ 
     "plotTypes" => Collection {#769 ▼ 
     #items: array:1 [▼ 
      0 => ProjectsPlotTypes {#774 ▼ 
      #table: "projects_plot_types" 
      #fillable: array:2 [▶] 
      +timestamps: false 
      #connection: null 
      #primaryKey: "id" 
      #perPage: 15 
      +incrementing: true 
      #attributes: array:4 [▼ 
       "id" => "2" 
       "project_id" => "1" 
       "name" => "TYPE 3 - VENTILATION" 
       "budget" => "245.69" 
      ] 
      #original: array:4 [▶] 
      #relations: [] 
      #hidden: [] 
      #visible: [] 
      #appends: [] 
      #guarded: array:1 [▶] 
      #dates: [] 
      #dateFormat: null 
      #casts: [] 
      #touches: [] 
      #observables: [] 
      #with: [] 
      #morphClass: null 
      +exists: true 
      +wasRecentlyCreated: false 
      } 
     ] 
     } 
    ] 
    #hidden: [] 
    #visible: [] 
    #appends: [] 
    #guarded: array:1 [▶] 
    #dates: [] 
    #dateFormat: null 
    #casts: [] 
    #touches: [] 
    #observables: [] 
    #with: [] 
    #morphClass: null 
    +exists: true 
    +wasRecentlyCreated: false 
    } 

回答

1

您也可以使用連接查詢像下面

$result = Illuminate\Support\Facades\DB::table('projects') 
     ->join('projects_plot_types', 'projects_plot_types.id', '=', 'projects.project_plot_id') 
     ->where('projects_plot_types.name', '=', $row->plot_name) 
     ->first(); 
print_r($result); 
1

可能,這是你在找什麼:

$result = $project->with(['plotTypes' => function($query) use ($row) { 
    return $query->where('name', $row->plot_name)->first(); 
}])->first(); 

dd($result); // print the result and die 

更新1

讀取第一來自具有BelongsTo關係的集合的物品:

$plotTypeResult = $result->plotTypes[0]->id; 

希望這可以幫助你。快樂編碼。乾杯。

+0

謝謝,但我怎麼然後訪問plotTypes ID? '$ result-> id'會打印項目ID大概? – V4n1ll4

+0

'$ result-> plotTypes() - > first() - > id'應該得到它你正在尋找的。 –

+0

這段代碼似乎仍然沒有獲取我需要的行。 – V4n1ll4