You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel新手求助:属性获取失败及Eloquent查询无结果问题

Troubleshooting Your Laravel Eloquent Query Issue

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 of get(). This returns a single model instance (or null if 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:

  1. 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)
    
  2. 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 named campaignss (double 's') by default. If your table is actually named campaigns, add this to your Campaigns model:
    protected $table = 'campaigns';
    
  • Verify field types: Make sure minage and maxage are numeric fields (INT, BIGINT, etc.) in your database. If they're stored as strings, the comparison logic might not work as expected.
  • Check the orderBy field: Does your table actually have a column named first? If not, remove that clause or replace it with a valid column name (like created_at).

内容的提问来源于stack exchange,提问作者programmers_39

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:17:50