【发布时间】:2020-02-18 06:10:33
【问题描述】:
namespace App;
use App\Model\Service\Area;
use App\Model\Bid\Service;
use Illuminate\Database\Eloquent\Model;
class Bid extends Model
{
protected $table = "bid";
protected $primaryKey = 'bid_id';
protected $guarded = [];
protected $with = ['services'];
public function services() {
return $this->hasMany(Service::class, 'bid_id');
}
public function area() {
return $this->belongsTo(Area::class, 'area_id', 'area_id');
}
}
namespace App\Model\Service;
use Illuminate\Database\Eloquent\Model;
class Area extends Model
{
protected $table = "location_area";
protected $primaryKey = 'area_id';
protected $guarded = [];
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
}
当我尝试访问时
Bid::with('area')->find(BID_ID);
返回 Null 查询触发错误:
"select * from `location_area` where `location_area`.`area_id` in (0)"
但如果我这样做:
$bid = Bid::find(BID_ID);
dd($bid->area);
它返回区域表值。出了什么问题?请帮我。一世 我有这个问题很长时间了。提前谢谢你:)
【问题讨论】:
-
嗨,你的控制器看起来怎么样?你返回什么?
-
您的区域表和投标表中是否都有
area_id列? Area 表上是否有一行具有特定的area_id? -
尝试更改
Bid.phppublic function area() { return $this->hasOne(Area::class, 'area_id', 'area_id'); } -
location_area表中有相关数据吗? -
@balkal 我正在使用 Axios 将来自我的 Vue 组件的请求传递给控制器,以获取有关特定出价的数据。路由器:
Route::middleware('auth')->group(function () { Route::get('/fetch/bid/{id}', 'UserController@bid')->where('id', '[0-9]{15}+'); });控制器:class UserController extends Controller { public function bid($bid_id) { return Bid::with('area')->findOrFail($bid_id); } }
标签: php laravel laravel-5 eloquent laravel-5.8