dongqian5569
2016-11-17 02:37
浏览 68
已采纳

Laravel Relation Query / Find - 尝试获取非对象的属性

I'm not able to fix this error when I tried associate category to transaction.

// TransactionController

$transactions = DB::table('transactions')
        ->where('status', 'false')
        ->orderBy('date','asc')
        ->get();        

        foreach($transactions as $data) {
            $transaction = new Transaction();
            $transaction->id = $data->id;
            $transaction->category = Transaction::find($data->categories_id)->category;
            $transaction->description = $data->description;
    }

The error occurs at time: ErrorException in TransactionController.php line 80: Trying to get property of non-object

Line 80: $transaction->category = Transaction::find($data->categories_id)->category;

But, if I test my code with die, that's result:

die(Transaction::find($data->categories_id)->category()->first());

{"id":1,"users_id":1,"description":"Alimenta\u00e7\u00e3o","created_at":"2016-11-15 20:31:11","updated_at":"2016-11-15 20:31:11"}

// Transaction Model

class Transaction extends Model
{
    public function category(){
        return $this->hasOne('App\Category','id');
    }  

[]'s

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhanzhen8927 2016-11-17 03:15
    已采纳

    You are getting that error as one or multiple $data->categories_id are not matching the id on the transactions table.

    Note: It's not a good practice to find a model and call a function on it on the same line as you have done.

    Transaction::find($data->categories_id)->category;

    Because, you never know what id will be passed as argument to find(). Better go for findOrFail().

    $tran = Transaction::findOrFail($data->categories_id);
    
    $cat = $tran->category;
    

    The findOrFail() function will throw a ModelNotFoundException whenever the id doesn't match in the transactions table. This exception can be easily handled by try...catch block.

    点赞 评论

相关推荐 更多相似问题