Laravel新手求助:属性获取失败及Eloquent查询无结果问题
Hey there, let's work through this problem together since you're new to Laravel—no worries, we'll get it sorted out!
First, Fix the Redundant Query Logic
Looking at your code, you've got identical conditions in both the initial where clause and the nested orWhere closure. That means your query is essentially filtering for the same thing twice, which doesn't add any value and might be throwing off your results (or just making the query inefficient).
If your goal is to find campaigns where the user's age falls between minage and maxage, you can simplify the query drastically:
$age = 24; $campaigns = Campaigns::select('id', 'startdate', 'enddate') ->where('minage', '<', $age) ->where('maxage', '>', $age) ->orderBy('first', 'DESC') ->get();
(Note: I renamed the variable to $campaigns since get() returns a collection of items, not a single campaign—this helps avoid confusion later!)
Fix the "Cannot Get Property" Error
That error usually pops up when you try to access a property on an empty collection or non-object. Here's how to handle it properly:
- If you expect a single campaign result, use
first()instead ofget(). This returns a single model instance (ornullif no results exist):$campaign = Campaigns::select('id', 'startdate', 'enddate') ->where('minage', '<', $age) ->where('maxage', '>', $age) ->orderBy('first', 'DESC') ->first(); // Safely access properties only if the campaign exists if ($campaign) { echo $campaign->id; } else { echo "No matching campaign found"; } - If you expect multiple results, always check if the collection is empty before trying to access properties:
if ($campaigns->isNotEmpty()) { foreach ($campaigns as $campaign) { echo $campaign->startdate; } } else { echo "No campaigns match your criteria"; }
Debugging Steps to Verify Your Query
If you're still not getting results, let's debug the actual SQL being generated to pinpoint the issue:
- Print the raw SQL query to see what's being sent to the database:
$query = Campaigns::select('id', 'startdate', 'enddate') ->where('minage', '<', $age) ->where('maxage', '>', $age) ->orderBy('first', 'DESC'); dd($query->toSql()); // Outputs the raw SQL string dd($query->getBindings()); // Shows the values being bound to the query (like $age=24) - Run that SQL directly in your database tool (like phpMyAdmin or TablePlus). If it returns results there but not in Laravel, you know the issue is with your model or setup, not the query logic.
Other Potential Issues to Rule Out
- Check your model's table name: Laravel assumes your table name is the lowercase plural of your model name. Since your model is
Campaigns, Laravel will look for a table namedcampaignss(double 's') by default. If your table is actually namedcampaigns, add this to yourCampaignsmodel:protected $table = 'campaigns'; - Verify field types: Make sure
minageandmaxageare numeric fields (INT, BIGINT, etc.) in your database. If they're stored as strings, the comparison logic might not work as expected. - Check the
orderByfield: Does your table actually have a column namedfirst? If not, remove that clause or replace it with a valid column name (likecreated_at).
内容的提问来源于stack exchange,提问作者programmers_39

