我正在尝试使用 Laravel 4 解决我的应用程序的问题。问题在于 Eloquent 和 M:M 关系。
这是我的情况:我有很多用户可以选择很多服务,他们可以为每项服务提供专门的价格。在数据库中,我有名为“services”、“users”和“users_services”的表。所以目前我可以保存每个用户选择的服务和价格但我的问题是我不知道如何检索并将它们展示给用户,我的意思是我不知道如何设置“检查”每个选定服务的复选框以及每项服务的价格。
您可以在 Paste Laravel 上查看代码以获取任何分叉。我也贴在这里。
<?php
class Service extends Eloquent {
public static $rules = array();
protected $guarded = array('id');
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'services';
/**
* -------------------------------------
* All Joins w/ other tables
* -------------------------------------
**/
public function users()
{
return $this->belongsToMany('User','users_services','services_id','user_id');
}
}
......
<?php
class User extends Eloquent {
public static $rules = array();
protected $guarded = array('id');
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* -------------------------------------
* All Joins w/ other tables
* -------------------------------------
**/
public function services()
{
return $this->belongsToMany('Service','users_services','user_id','service_id');
}
}
................
// Inside the controller
$services = Service::all();
$this->layout->content = View::make('private.user.services')->with(compact('services'));
...............
// The view
@foreach($services as $service)
<div class="pull-left col-lg-6 service-container">
<div class="checkbox pull-left">
<label>
<input type="checkbox" name="services[]" value="{{ $service->id }}"><span>{{ $service->name }}</span>
</label>
</div>
<div class="input-group service-price pull-right">
<input type="number" min="0" name="prices[{{$service->id}}]" class="form-control pull-rigth" placeholder="0">
<span class="input-group-btn">
<button class="btn btn-default" type="button" disabled><i class="icon-eur"></i></button>
</span>
</div>
</div>
@endforeach