2016-02-21 25 views
0

我有2個表,usersprofiledetails聯接查詢在laravel與數據操作發送到瀏覽

我能跑加入查詢和訪問數據和發送來查看。

但是,當我操縱字段'dob'(日期格式)在profiledetails表中。沒有成功,請檢查下面的代碼,

webpagesConroller

$users = DB::table('users') 
     ->join('profiledetails', 'users.id', '=', 'profiledetails.user_id') 
     ->select('users.*', 'profiledetails.dob') 
     ->get(); 
    $age = $users->dob->diffInYears(Carbon::now());   
    return view('webpages.index',compact('users'))->with($age); 

View:

<li class="cate_head">Age : {{ $age}}</li> 

錯誤:

Trying to get property of non-object 

我已經模型Profiledetails加入存取器下面,

public function getAge(){ 

     return $this->dob->diffInYears(Carbon::now());    

    } 

    public function getDOB(){ 
     return $this->dob->format('d-m-Y'); 
    } 

我不能在另一個控制器上使用此方法作爲Ex-webpagesController,如果是的話如何。

回答

0

由於您使用的是原始查詢,返回的數據不是對象,而是包含數據的數組。

此外,您沒有限制查詢,這意味着它可能會返回多行。 您可能會需要得到從$用戶的數據爲:

//with the possibily of multiple rows. Index is the row which has to be used 
$users[index]['dob'] 

//when you are sure it only returns one row 
$users[0]['dob'] // or $users['dob'] not sure as of the moment 

你想檢查與碳的差異。 因此,您可能需要製作dob結果的Carbon對象,並根據Carbon ::現在進行檢查。

$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();  
// diffForHumans() uses the local time 

請注意,這隻獲得一行的年齡(索引或第一個因爲[0])。

如果你想爲每一行使用一個for或foreach,你爲每個$ user設置$ users-> age。但是,因爲這些不是對象/模型,而是原始數據,所以這是行不通的。

希望這可以幫助你的問題