如何获取关系中的表的id以在此关系中的其他表中使用?

时间:2017-11-22 08:10:12

标签: php laravel laravel-5 laravel-5.5

我在ServiceServices_Gallery之间有一对多关系,我想在Service插入新图片时使用Services_Gallery的ID,这是我的控制器:

public function save(Request $request)
{
    $this->validate($request,[
        'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
    ]);

    $services_Gallery               = new Services_Gallery();
    $services_Gallery->image        = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
    $services_Gallery->Service::all(id) = $request->service_id; //The problem here 
    $services_Gallery->save();
    return back();
}

这是我的模特:

class Service extends Model
{
protected $table = 'services';
protected $fillable = [
    'en_main_title',
    'ar_main_title',
    'en_sub_title',
    'ar_sub_title',
    'en_content_title',
    'ar_content_title',
    'en_content',
    'ar_content',
    'priority',
];

public function gallery()
{
    return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
    'image',
    'service_id',
];

public function gallery(){
    return $this->belongsTo('App\Service','service_id');
}
}

1 个答案:

答案 0 :(得分:0)

Exapmle:

$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;

你需要吗?