Laravel 5.5 ORM关联指定字段查询后orders_currency为空问题
Hey there, let's break down why your orders_currency relationship is returning empty even though you've selected the id field. Here are the most common culprits to check:
1. You're missing the foreign key in your select clause
This is probably the biggest issue here. When Laravel loads related Order records, it needs the trip_id field to match against the parent Trip's id. Right now, your select() only includes id and converted_currency_code—you haven't included trip_id! Without that field, Laravel can't map which Order records belong to the current Trip, so it returns an empty collection.
Fix it by adding trip_id to your select:
public function orders_currency() { return $this->hasMany('App\Order', 'trip_id', 'id') ->select('id', 'trip_id', 'converted_currency_code'); }
2. Verify the foreign key and primary key match correctly
Double-check these details:
- The
orderstable actually has atrip_idcolumn (typos are easy to miss!) - The data type of
trip_idinordersmatches theidtype intrips(e.g., both are unsigned integers with the same length) - There are actual
Orderrecords in your database wheretrip_idmatches theidof theTripinstance you're working with. Run a quick raw SQL query to confirm:SELECT * FROM orders WHERE trip_id = [your_trip_id];
3. Check your model namespace (for Laravel 8+)
If you're using Laravel 8 or newer, the default model namespace is App\Models, not App. So if your Order model lives in app/Models/Order.php, update your relationship to reference the correct namespace:
return $this->hasMany('App\Models\Order', 'trip_id', 'id') ->select('id', 'trip_id', 'converted_currency_code');
4. Soft deletes might be hiding records
If your Order model uses the SoftDeletes trait, Laravel automatically excludes records marked as deleted. To test if this is the case, add withTrashed() to your relationship:
public function orders_currency() { return $this->hasMany('App\Order', 'trip_id', 'id') ->select('id', 'trip_id', 'converted_currency_code') ->withTrashed(); }
If records show up after this change, you know the issue was soft-deleted orders being filtered out.
5. Ensure you're loading the relationship correctly
Make sure you're accessing the relationship properly:
- Eager loading: Use
with('orders_currency')when fetching theTripto load the relationship upfront:$trip = Trip::with('orders_currency')->find($tripId); - Lazy loading: Access the relationship on an existing
Tripmodel instance (not a query builder):$trip = Trip::find($tripId); $orders = $trip->orders_currency; // Triggers lazy loading
Trying to access the relationship directly on a query builder (like Trip::where('id', $tripId)->orders_currency) won't work—you need to fetch the actual model first.
内容的提问来源于stack exchange,提问作者Abeera

