【问题标题】:Laravel Eloquent activity feedLaravel Eloquent 活动提要
【发布时间】:2015-12-01 17:08:15
【问题描述】:

我正在尝试创建一个简单的活动供稿,用户可以在其中看到他朋友的更新。

我正在处理三张桌子。 user_status、友谊和用户。

用户表

user_id
name
email
..(a regular users table, nothing special)

友谊表

friendship_id
friend_one (Foreign key from users table)
friend_two (Foreign key from users table)

用户状态表

status_id
user_id (foreign key from users table)
status
date

模型

用户模型

public function friends() {
    return $this->belongsToMany('App\Models\User', 'friendship', 'friend_one', 'friend_two');
}

public function status() {
        return $this->hasMany('\App\Models\UserStatus','status_id');
    }

用户状态模型

public function usersStatus() {
    return $this->belongsTo('\App\Models\User','user_id');
}

FeedController.php

class FeedController extends Controller
{
    public function index() {

        $friends = Auth::user()->friends;


        return view('frontend.feed.index')
          ->with('friends',$friends);
    }

}

使用下面的查询,我可以获得用户的朋友。我也可以轻松获取特定用户的状态更新,但我不知道如何仅列出特定用户的状态。

@foreach($friends as $friend)
    {{$friend->email}}
@endforeach

下面那个不行。

查看

@foreach($friends as $friend)
    @foreach($friend->status as $status)
        {{$status->status}}
    @endforeach
@endforeach


Invalid argument supplied for foreach() (View: /Applications/MAMP/htdocs/master/resources/views/frontend/feed/index.blade.php)

【问题讨论】:

    标签: eloquent laravel-5.1


    【解决方案1】:

    我认为问题在于您在

    中的 foreign_key 引用
    public function status() {
            return $this->hasMany('\App\Models\UserStatus','status_id');
    }
    

    改为:

    public function status() {
            return $this->hasMany('\App\Models\UserStatus', 'user_id', 'user_id');
    }
    

    它应该可以工作。

    【讨论】:

    • 它不起作用,我得到同样的错误。请问为什么关系中有两个user_id?
    • 由于您没有使用默认 ID,因此您必须以 $this->hasMany('App\Models\UserStatus, 'foreign_key', 'local_key') 格式覆盖 local_key 和 foreign_key 引用.现在因为你的 foreign_key 和 local_key 都是 user_id。 laravel.com/docs/5.1/eloquent-relationships#one-to-many
    • 还有为什么你的 UserStatus 模式中有一个 usersStatus() 方法。它应该是 user()。
    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多