Laravel试图查询关联模型hasMany

时间:2016-03-16 09:48:11

标签: php laravel laravel-5

我的申请表中有以下表格:

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
  }

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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);