【问题标题】:Laravel eloquent with() returns nullLaravel 雄辩的 with() 返回 null
【发布时间】: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');
    }
}

Area table Migration and data

Bid table Migration and data

当我尝试访问时

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.php public 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


【解决方案1】:

在您的出价模型中更改此功能:

 public function area() {
        return $this->belongsTo(Area::class, 'area_id');
    }

【讨论】:

    【解决方案2】:

    您必须在您的MID 模型

    中声明一个方法
        public function area()
            {
                return $this->belongsTo(Area::class, 'bid');
            }
    

    类似的东西 在此之后,您访问with()中的区域

    Bid::with('area')->find(BID_ID);
    

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 2018-01-14
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 2018-04-11
      • 2020-02-17
      相关资源
      最近更新 更多